Deep Parekh Deep Parekh - 7 months ago 202
HTML Question

Disable 2nd dropdown option based on first dropdown

I have two dynamic dropdowns but both dropdown's value and options are same. What I want that if user select 'apple' from first dropdown then the second dropdown's apple option will be disabled (using javascript). In short user can not select same value from both.

//first drop down
<select name="fruit1">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>

//second dropdown
<select name="fruit2">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>


I have tried with jQuery:

function witness()
{
var op=document.getElementById("witness1").value;
$('option[value='+op+']').prop('disabled', true);
}


But with this both dropdown's value are disabled and if I select mango then apple will not enabled it remains disabled. I know I did not pass id so both dropdown value are disabled but where should i pass ?

If user select apple then in second dropdown apple will be disabled, I want to do this using Javascript or jQuery.

Answer

Try this out:

HTML:

<select id='fruit1' onchange="witness();">
    <option selected></option>
    <option value="1">Apple</option>
    <option value="2">Mango</option>
</select>

<select id='fruit2'>
    <option selected></option>
    <option value="1">Apple</option>
    <option value="2">Mango</option>
</select>

JQuery:

function witness(){
    $("#fruit2 option").each(function(){
        if($("#fruit1 option:selected").val() == $(this).val())
            $(this).attr("disabled", "disabled");
        else
            $(this).removeAttr("disabled");
    });
}

You can see a working exemple here: https://jsfiddle.net/mqjxL4n0/

Comments