Maff Maff - 1 month ago 6
HTML Question

Change dropdown options if radio button selected

I have 3 radio buttons selected, if the user chooses one of them I am wanting all but 2 options to disappear from a dropdown list further down the page, can anyone help please? If someone selects the third option (id="notify_type3") then I only want the dropdown to show an initial "select" (

<option value="">Please select</option>
) and one other option (for example,
<option value="4">Option 4</option>
), if the other 2 radio buttons are selected then it needs to show the whole list.

Staff member
<input type="radio" name="notify_type" id="notify_type1" value="new member of staff">
Editorial Freelance
<input type="radio" name="notify_type" id="notify_type2" value="new freelance user">
Contractor/Consultant
<input type="radio" name="notify_type" id="notify_type3" value="new contractor user">

<select class="dropdown" name="starter_company" id="starter_company">
<option value="">Please select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
</select>

Answer

I would probably hide the drop down menu entirely until the user selects an option, and then display it. But I would do something like this, that way, if they change the radio button back your options will re-appear.

Here's a fiddle.

$("input[type='radio'][name='notify_type']").change(function(){

    var selected = $("input[type='radio'][name='notify_type']:checked").val();

    if(selected == "new contractor user") var opts = [
        {name:"Please Select", val:""},
        {name:"Option 4", val:"4"}
    ];

    else var opts = [
        {name:"Please Select", val:""},
        {name:"Option 1", val:"1"},
        {name:"Option 2", val:"2"},
        {name:"Option 3", val:"3"},
        {name:"Option 4", val:"4"}
    ];

    $("#starter_company").empty();

    $.each(opts, function(k,v){

        $("#starter_company").append("<option value='"+v.val+"'>"+v.name+"</option>");

    });
});
Comments