Remove option in select

前端 未结 4 950
执念已碎
执念已碎 2021-01-25 19:24

                        
    
提交评论

  • 2021-01-25 19:47

    It will be easy if you use different class for second and third select element

    $(".one").change(function(){
        var val = parseInt($(this).val());
        $('.two,.three').find('option:contains('+val+')').remove();  
    });  
    

    EDIT:
    Updated code to apply for multiple selects. [Thanks to all commentators and Alex for bringing it to notice ]

      $(".one").change(function(){
            var val = parseInt($(this).val());
            $(this).siblings().find('option:contains('+val+')').remove();  
        });  
    
    0 讨论(0)
  • 2021-01-25 19:53

    Here you go http://jsfiddle.net/Calou/9N9Tz/6/.

    When the value of the <select>s changes, just take this value and search for the <option>s with this value in the others <select>s and remove them.

    $(".one").change(function(){
        var val = this.value
        if (val !== '') {
            $(this).siblings().find('option[value=' + val + ']').remove()
        }
    })
    
    0 讨论(0)
  • 2021-01-25 20:02

    If you need to sort something, consider using something like jQuery UI sortable as a bunch of drop down menus make a really poor UX for that.

    But to answer your question:

    var $selects = $('.one');
    $selects.on("keyup click change", function(e) {
      $selects.not(this).trigger('updateselection');
    }).on("updateselection", function(e, data) {
      var $this = $(this);
      $this.children().show();
      $selects.not(this).each(function() {
        var value = $(this).val();
        if (value) {
          $this.children('[value="' + value + '"]').hide();
        }
      });
    });
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select class="one">
      <option></option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <br />
    <select class="one">
      <option></option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <br />
    <select class="one">
      <option></option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    

    Hiding an option works in current firefox. I'm not sure about legacy browser. Hiding, but not removing, the element makes sure that you can change your selection without having crippled your input elements.

    0 讨论(0)
  • 提交回复
    热议问题