Change the visibility of forms depending on the selected option

I am creating a research form that will display differently depending on the choice of the SELECT value. I applied some jQuery tricks after searching here. Unfortunately, this does not work at all. Here is my code:

HTML:

<select name="options" id="choice"> <option value="0" selected="true">Choose...</option> <optgroup label='ABC'> <option value="1">...DEF</option> <option value="2">...GHL</option> </optgroup> <optgroup label="MNP:"> <option value="3">X</option> <option value="4">Y</option> <option value="5">Z</option> </optgroup> </select> <form id="opt1" name="opt1" style="display: none">11111111</form> <form id="opt2" name="opt2" style="display: none">22222222</form> <form id="opt3" name="opt3" style="display: none">33333333</form> <form id="opt4" name="opt4" style="display: none">44444444</form> <form id="opt5" name="opt5" style="display: none">55555555</form> 

JavaScript:

 $("#choice").change(function() { $("form").hide(); $("#opt" + $(this).val()).show(); }); 
+5
source share
3 answers

Try this one

 $(document).ready(function(){ $('select').change(function() { //var selected = $(':selected', this); //alert(selected.closest('optgroup').attr('label')); $("form").hide(); $("#opt" + $(this).val()).show(); }); }); 

Demo here

+1
source

A @guradio suggests, the code works fine in the fiddle. To debug the problem, try setting alert or console.log() to find out what the problem is. I hope you have a jQuery library added to your page.

Try the following:

 $("#choice").change(function() { alert('fine till here'); $("form").hide(); $("#opt" + $(this).val()).show(); }); 
0
source

Your code works, I think you are missing the j query library in the form. add.

see jsfiddle.net/f5xuc0gh/

0
source

Source: https://habr.com/ru/post/1246913/


All Articles