Removing an Item from a dropdown when selected in

2020-02-12 12:16发布

问题:

This page will have 16 dropdown boxes, when I select an item from each of them, I'd like it to be removed from all the others.

This is for a football lineup page, if that helps you picture the scenario.

I hope this isn't too vague and I'm clear in what I'm struggling with.

Thanks :)

I am using in the whole project: HTML, PHP, Javascript, AJAX

<select name="pl1">
  <option value="1">Ben</option>
  <option value="2">Jack</option>
  <option value="3">James</option>
  <option value="4">John</option>
</select>

<select name="pl2">
  <option value="1">Ben</option>
  <option value="2">Jack</option>
  <option value="3">James</option>
  <option value="4">John</option>
</select>

<select name="pl3">
  <option value="1">Ben</option>
  <option value="2">Jack</option>
  <option value="3">James</option>
  <option value="4">John</option>
</select>

<select name="pl4">
  <option value="1">Ben</option>
  <option value="2">Jack</option>
  <option value="3">James</option>
  <option value="4">John</option>
</select>

回答1:

Javascript solution:

function check() {
  d=document;
  myArray = [];
  for (h=0;h<4;h++) {
    myArray[h] = d.getElementById('pl'+(h+1)).value;
  }
  for (a=0;a<4;a++) {
    for (b=1;b<5;b++) {
    d.getElementById('pl'+(a+1)).options[b].style.display = "block";
      for (c=0;c<4;c++) {
        if(d.getElementById('pl'+(a+1)).options[b].value == myArray[c]) {
          d.getElementById('pl'+(a+1)).options[b].style.display = "none";
        }
      }
    }
  }
}

HTML:

<select id="pl1" onchange="check();">
  <option value="">Choose</option>
  <option value="1">Ben</option>
  <option value="2">Jack</option>
  <option value="3">James</option>
  <option value="4">John</option>
</select>

<select id="pl2" onchange="check();">
  <option value="">Choose</option>
  <option value="1">Ben</option>
  <option value="2">Jack</option>
  <option value="3">James</option>
  <option value="4">John</option>
</select>

<select id="pl3" onchange="check();">
  <option value="">Choose</option>
  <option value="1">Ben</option>
  <option value="2">Jack</option>
  <option value="3">James</option>
  <option value="4">John</option>
</select>

<select id="pl4" onchange="check();">
  <option value="">Choose</option>
  <option value="1">Ben</option>
  <option value="2">Jack</option>
  <option value="3">James</option>
  <option value="4">John</option>
</select>

Make sure you use id and not name on your select's



回答2:

Using jQuery:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jQuery</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>

        <script type="text/javascript">
            $(function () {
                var selects = $('select.magic-select');
                $(selects).bind('change', function (evt) {
                    var newVal = $(this).val(), oldVal = $(this).data('old-val');

                    if (newVal != 0) {
                        $(selects).not(this).find('option[value="' + newVal + '"]').attr('disabled', 'disabled');
                    }

                    $(selects).not(this).find('option[value="' + oldVal + '"]').removeAttr('disabled');
                    $(this).data('old-val', newVal);
                });
            });
        </script>
    </head>

    <body>
        <?php
            $players = array('Ben', 'Jack', 'James', 'John', 'Foo', 'Bar', 'Allmighty Foobar');
            $numPlayers = count($players);

            for ($i = 1; $i <= $numPlayers; $i += 1) {
                printf('<select class="magic-select" name="pl%s" size="%s"><option value="0"></option>', $i, $numPlayers + 1);

                foreach ($players as $j => $name) {
                    printf('<option value="%s">%s</option>', $j + 1, $name);
                }

                echo '</select>';
            }
        ?>
    </body>
</html>

Note that magic-select as a class name is not a must. It could be anything, but you'll have to adjust the javascript accordingly.



回答3:

Prototype solution:

$$('select').each(function(item) {
    Event.observe(item, 'change', function(e) {
        var el = e.srcElement;
        var val = el.options[el.selectedIndex].innerHTML;
        $$('select').each(function(item) {
            if (item != el) {
                for (var i = 0; i < item.options.length; i++) {
                    if (item.options[i].innerHTML == val) {
                        item.removeChild(item.options[i]);
                    }
                }
            }
        });
    });
});

http://jsfiddle.net/qrhe7/



回答4:

I have taken @Tokes answer and made it a little more understandable and added some jQuery to it for dropdown and option selection. I am providing this incase someone struggles with getting it implemented. I am using the most direct selectors possible so jQuery doesn't have to work so hard. I am using this logic on 68 drop downs with 68 options in it, the performance was kinda bad when I started due to jQuery and the amount of for loops I was using but now it is really snappy so I hope someone gets some use out of it. Thanks Tokes your answer helped for my situation :)

function _updateDropdowns() {

    // gather selects with class so we dont grab all
    var select = $('#tbl_fieldMap select.table-fields');

    // store used fields
    var used = [];

    // collect all selected values
    for (var x = 0; x < select.length; x++) {

        // get selects value
        var val = select[x].value;

        // dont add empty
        if (val != '')
            used[x] = val;
    }

    // foreach select box
    for (var a = 0; a < select.length; a++) {

        // get options that matter (excludes 'default entry')
        var options = $(select[a]).children('.table-option');

        // foreach option in select
        for (var c = 0; c < options.length; c++) {

            // current option
            var opt = options[c];

            if ($.inArray(opt.value, used) > -1) {
                // hide if already used
                opt.style.display = "none";
            } else {
                // show if not used
                opt.style.display = "block";
            }
        }
    }
}


回答5:

.data() = Store arbitrary data associated with the specified element and/or return the value that was set.

.not() = Remove elements from the set of matched elements.

.on() = will attach an event handler function for one or more events to the selected elements(change in this case)

.find() = Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. in this case well find the element that has been used and put in in a var named prevValue, then we check if there is a match with the other selection fields and then removes those from the selection options.

$(document).ready(function(){

$('select').on('change', function(event ) {
   var prevValue = $(this).data('previous');

$('select').not(this).find('option[value="'+prevValue+'"]').show();    
   var value = $(this).val();

    $(this).data('previous',value);         
    $('select').not(this).find('option[value="'+value+'"]').hide();

  });

});