多个选择禁用彼此的选项

时间:2013-06-18 23:13:20

标签: jquery select

我正在使用一个很棒的jQuery函数,当页面上有多个选择时,它会禁用相等选项值的选择。问题是我不知道它是怎么做的。

JSFiddle链接:http://jsfiddle.net/Z2yaG/4/

这是jQuery函数的外观:

var prev = -1;
$("select").change(function () {
    if ($(this).val() > -1) {
            $("select").not(this).find("option[value=" + $(this).val() + "]").attr('disabled', 'disabled');
            $("select").not(this).find("option[value=" + previous + "]").removeAttr('disabled');}
    else {
             $("select").not(this).find("option[value=" + previous + "]").removeAttr('disabled');
         }
     }).focus(function () {
previous = $(this).val();
});

这是如何工作的?

1 个答案:

答案 0 :(得分:3)

var previous = -1;
// Setting a previously selected value
$("select").change(function () {
// When any select element is changed
    if ($(this).val() > -1) {
    // When value is > -1
        // Get all selects but not the current one which triggered the change event
        $("select").not(this)
           .find("option[value=" + $(this).val() + "]").attr('disabled', 'disabled');
        // set the current option value to disabled

         // Get all selects but not the current one which triggered the change event
        $("select").not(this)
            .find("option[value=" + previous + "]").removeAttr('disabled');
        // Remove the disabled property on previous value
    } else {
        // Get all selects but not the current one which triggered the change event
        $("select").not(this)
            .find("option[value=" + previous + "]").removeAttr('disabled');
        // Remove the disabled property
    }
}).focus(function () {
    previous = $(this).val();
    // store the current value of the select to previous 
});