I am trying to show and hide fields with respective selected value from tag. But it is not working. This same code is working perfectly in my other site. But it is not working here, don’t know which thing i am missing. Here is the code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="col-md-12 col-sm-12 col-lg-12"> <label>Product Type <sup>*</sup></label> <div class="select-wrp"> <script> $('select') .change(function () { if ($(this).val() === 'single') { $('.single').show(); $('.multiple').hide(); } else { $('.multiple').show(); $('.single').hide(); } }) .change(); </script> <select name="product_type"> <option value="single">Single</option> <option value="multiple">Multiple</option> </select> </div> </div> <div class="col-md-12 col-sm-12 col-lg-12"> <input class="single" name="single" type="text" placeholder="100" /> <input class="multiple" name="multiple" type="text" placeholder="100" /> </div>
Advertisement
Answer
Your script needs to be told to wait for the window to be loaded first. You can use jQuery to do this by simply adding $(() => { ... })
around your existing script:
$(() => { $('select').change(function () { if ($(this).val() === "single") { $('.single').show(); $('.multiple').hide(); } else { $('.multiple').show(); $('.single').hide(); } }).change(); });
Natively, you would use window.onload = () => { ... };
instead.