Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...