Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
294 views
Welcome To Ask or Share your Answers For Others

1 Answer

Fiddle: https://jsfiddle.net/3pfo1d1f/

To get the functionality you're after, you need to hook into the change event on the first dropdown, in order to disable the matching element in the second drop-down.

I also initialised the first element in the second dropdown as disabled ( as this chosen by default in the first dropdown)

Used jquery as you are:

HTML:

<!-- first dropdown -->
<select id="fruit1">
    <option value="1">Apple</option>
    <option value="2">Mango</option>
</select>

<br /> <br />

<!-- second dropdown -->
<select id="fruit2">
    <option value="1" disabled>Apple</option>
    <option value="2">Mango</option>
</select>

JQuery:

$('#fruit1').on( "change", function() {
    var op = $( this ).val();
    $('#fruit2 option').prop('disabled', false);
    $('#fruit2 option[value='+op+']').prop('disabled', true);
});

This should still work, no matter how many options you have in both the dropdowns


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...