jQuery - Remove a drop down item if it is selected by user

javascript, jquery

Solution

Maybe this can feed your needs:

SEE DEMO

var $selects = $('select');
$('select').change(function () {
    $('option:hidden', $selects).each(function () {
        var self = this,
            toShow = true;
        $selects.not($(this).parent()).each(function () {
            if (self.value == this.value) toShow = false;
        })
        if (toShow) $(this).show();
    });
    if (this.value != 0) //to keep default option available
      $selects.not(this).children('option[value=' + this.value + ']').hide();
});

Problem

I have 4 drop down lists with a list of teams in drop down list taken from a database. I've put the code for the drop down lists below, I apologise it is written in JADE's template engine for HTML but this is how I've written the code. I have put my current jQuery script below as well. At the moment, it sort of works, if I go from team 1 through to team 4 and select a team, then it works, but if I change my mind for one of the drop downs...then the whole list messes up as it has already removed certain items... If I enter a team in team1, it should disappear from the rest of the lists....but if I change team 1, the team should appear in the rest of the lists again, but it doesnt at the moment. Any ideas how to fix this? JADE drop downs: ``` div.row label.control-label(for="team1") Team 1: div.controls select#team1(style='width: 160px;') include teamsDropDown div.row label.control-label(for="team2") Team 2: div.controls select#team2(style='width: 160px;') include teamsDropDown div.row label.control-label(for="team3") Team 3: div.controls select#team3(style='width: 160px;') include teamsDropDown div.row label.control-label(for="team4") Team 4: div.controls select#team4(style='width: 160px;') include teamsDropDown ``` teamsDropDown JADE: ``` -if(teamsList.length > 0){ option -each team in teamsList option.teamDropDown(id="#{team.key}",value="#{team.key}") #{team.name} -}else{ No teams till now.. -} ``` jQuery script: ``` script(type='text/javascript') $('select').change(function() { $('select').not(this).children('option[value=' + $(this).val() + ']').remove(); }); ``` JFiddle: http://jsfiddle.net/m8QCZ/

Original source