Kishor Kumar
Kishor Kumar

Reputation: 543

Disabling one option in HTML listbox

I have 3 listboxes which displays same options. I want to disable the option in other two listboxes which is selected in a listbox. I want to let my User go any listbox first. Any help is appreciated.

Upvotes: 0

Views: 1807

Answers (2)

Didier Ghys
Didier Ghys

Reputation: 30666

If you have the following HTML:

<select id="select1">
    <option value="">Choose</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>

<select id="select2">
    <option value="">Choose</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>

<select id="select3">
    <option value="">Choose</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>

You can do this (with the help of jquery):

var previousValues = []
    $selects = $('#select1, #select2, #select3');

$selects
    .mousedown(function(e) {
        // save the previous value for re-enabling it when you change
        var val = $(this).val();
        if (val) {
            previousValues[this.id] = val;
        }
    })
    .change(function(e) {
        // get the other select elements
        var $theOtherSelects = $selects.not('#' + this.id),
            prevVal = previousValues[this.id],
            val = $(this).val();

        // re-enable the previously disabled option
        if (prevVal) {
            $theOtherSelects
                .find('option[value=' + prevVal + ']')
                .prop('disabled', false);
        }

        // if a value is selected, disble in the other selects            
        if (val) {
            $theOtherSelects
                .find('option[value=' + val + ']')
                .prop('disabled', true);
        }
    })
    .mousedown()
    .change();

Here's jsfiddle for you to play with.

Note: I've used jQuery because it is much easier, will work cross-browser, and you did not specify you didn't want to use it explicitly.

Upvotes: 2

Emil Lundberg
Emil Lundberg

Reputation: 7380

You could set some unique property on each option (the value might be enough, otherwise class is a good choice) and use jQuery to select and delete one option from the other two when it is selected in one of the selects.

EDIT: Here's an example that does something along the lines of what you want. You'd have to modify it a bit yourself. Didier's answer may be closer to what you want, though.

http://jsfiddle.net/baByZ/39/

Upvotes: 1

Related Questions