Ivan Pandžić
Ivan Pandžić

Reputation: 373

Multiple selects which disable each other's options

I'm using a great jQuery function which disables selection of equal option values, when there is a multiple selects on page. Problem is I don't know how it is doing.

JSFiddle link: http://jsfiddle.net/Z2yaG/4/

This is what jQuery function looks:

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();
});

How this WORKS????

Upvotes: 2

Views: 183

Answers (1)

Sushanth --
Sushanth --

Reputation: 55750

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 
});

Upvotes: 3

Related Questions