Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Disable a selected option if is selected already.

I need to disable a selection if it has been already selected.

<h4 class="info-text">Select 1st Employee<br>
    <select name="wcl-employees1" id="wcl-employees1">
        <option value="" disabled="" selected="" style="display:none;">Select One...</option>
        <option value="ALCANTARA, ERIC">ALCANTARA, ERIC</option>
        <option value="ALDRIGE, ,MERANDA">ALDRIGE, ,MERANDA</option>
        <option value="ALTOBELLI, JAMES">ALTOBELLI, JAMES</option>
    </select>
</h4>
<h4 class="info-text">Select 2nd Employee<br>
    <select name="wcl-employees2" id="wcl-employees2">
        <option value="" disabled="" selected="" style="display:none;">Select One...</option>
        <option value="ALCANTARA, ERIC">ALCANTARA, ERIC</option>
        <option value="ALDRIGE, ,MERANDA">ALDRIGE, ,MERANDA</option>
        <option value="ALTOBELLI, JAMES">ALTOBELLI, JAMES</option>
    </select>
</h4>
<h4 class="info-text">Select 3rd Employee<br>
    <select name="wcl-employees3" id="wcl-employees3">
        <option value="" disabled="" selected="" style="display:none;">Select One...</option>
        <option value="ALCANTARA, ERIC">ALCANTARA, ERIC</option>
        <option value="ALDRIGE, ,MERANDA">ALDRIGE, ,MERANDA</option>
        <option value="ALTOBELLI, JAMES">ALTOBELLI, JAMES</option>
    </select>
</h4>

If you select Eric in the first selection, I want the next to disable him from being able to be selected.

I am not a javascript guru, this might even be a simple process but I cant figure it out.

1 Answer

Hi Allen,

This was a bit of a mind bender for me, but I think this should work for your code as-is (tested successfully on my end); requires jQuery.

var $select = $("select");
$select.on("change", function() {
    var selected = [];  
    $.each($select, function(index, select) {           
        if (select.value !== "") { selected.push(select.value); }
    });         
   $("option").prop("disabled", false);         
   for (var index in selected) { $('option[value="'+selected[index]+'"]').prop("disabled", true); }
});

Thank you very much! Exactly what I was looking for.. :-)

EDIT (UPDATE): So this is for a form. Now, it does work when making a selection but when I post to a form, it actually doesn't go through. Any thoughts?