Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery <select> option disabled if selected in other <select>

I am trying to attempt to disable an option if it is selected in any of the selects

So for example if name="select1" has selected option "Test 2", then I want "Test 2" to be disabled in both select statements... and if something else gets checked that it re-enables the previous option.

I have written a sample script here to which I thought would get me 'close'... but it's put me far off base here. Any help would be appreciated.

<script type="text/javascript">
$(document).ready(function(){
 $("select").change(function() {
  $("select").find("option:selected").attr('disabled', true);
 });
});
</script>

<select name="select1">
    <option>No Match</option>
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

<select name="select2">
    <option>No Match</option>
    <option value="1">Test</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>
like image 917
Justin Avatar asked Jan 06 '11 00:01

Justin


1 Answers

Live demo: http://jsfiddle.net/dZqEu/

$('select').change(function() {

    var value = $(this).val();

    $(this).siblings('select').children('option').each(function() {
        if ( $(this).val() === value ) {
            $(this).attr('disabled', true).siblings().removeAttr('disabled');   
        }
    });

});

You may prefer this version of the code:

$('select').change(function() {

    $(this)
        .siblings('select')
        .children('option[value=' + this.value + ']')
        .attr('disabled', true)
        .siblings().removeAttr('disabled');

});

Live demo: http://jsfiddle.net/dZqEu/2/

Note that this second version is an one-liner (one line of code) but I formatted it to be more readable. I like this second version better.


Also, note that my code assumes that those two SELECT boxes are DOM sibling elements. If that's not your case, then this code - $(this).siblings('select') - will not work for you, and you will have to use jQuery's traversal methods to jump to the other SELECT box.

In the worst-case scenario - when the SELECT boxes are far apart in the DOM tree, and traversing would not be efficient - you can just assign ID attributes to them and use this code to select the other box:

$('#select1, #select2').not(this)

Live demo: http://jsfiddle.net/dZqEu/3/

like image 50
Šime Vidas Avatar answered Oct 24 '22 17:10

Šime Vidas