Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change visibility of forms depending on chosen option

I'm making a research form which will display differently depending on the choice of a SELECT value. I have applied some jQuery tricks after searching through here. Unfortunately, it doesn't 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();
});
like image 391
qnhant5010 Avatar asked Nov 09 '22 16:11

qnhant5010


1 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

like image 80
kakurala Avatar answered Nov 14 '22 21:11

kakurala