removing all options of select box except 1st option

前端 未结 8 2132
情书的邮戳
情书的邮戳 2020-12-29 01:20

I\'m trying to empty select options when:

id \"mClick\" is selected, id\'s \"sClick\", \"cClick\" and \"srClick\" will be emptied.

id \"sClick\" is selected,

相关标签:
8条回答
  • 2020-12-29 01:57

    It's Work

    $('#mClick').change(function () {
        $('#sClick, #cClick, #srClick').find("option:gt(0)").remove();
    });
    $('#sClick').change(function () {
        $('#cClick, #srClick').find("option:gt(0)").remove();
    });
    $('#cClick').change(function () {
        $('#srClick').find("option:gt(0)").remove();
    });
    
    0 讨论(0)
  • 2020-12-29 01:59

    you can use the greater than :gt() selector of jQuery for this

    $('#lForm select[id!="makeClick"] select[id!="stateClick"] select[id!="cityClick"] option:gt(0)').remove().end();
    

    This will remove all options that are greater than 0

    0 讨论(0)
  • 2020-12-29 02:06

    The easiest way to clear the options in the way you're describing is by using options.length = 1. Also, you can leverage the fact that each drop down clears the ones that logically follow it, so that you only need to declare a single change handler.

    $('#lForm select').on('change', function() {
      if (this.selectedIndex > 0) {
        var $others = $(this).closest('table').find('select'),
        current = $others.index(this); // find current
    
        while (++current < $others.length) {
          // for each following drop down
          $others.get(current).options.length = 1;
        }
      }
    });
    

    Demo

    I'm not sure how you're going to repopulate the drop downs though :)

    0 讨论(0)
  • 2020-12-29 02:09

    I was looking for one line code, what I found after lots of research is the Simplest and Best one line code to remove everything except first.

    JQuery,

    $('#ddlId option:not(:first)').remove();
    
    0 讨论(0)
  • 2020-12-29 02:12

    Try this

    $('#lForm select').change(function(){
       var $selects = $('#lForm select');
       var idx = $selects.index(this);
    
       // Use `val` function to clear the selected values or Use `remove` function to remove the element.
       $selects.filter(':gt(' + idx +')').val('');
    
    });
    
    0 讨论(0)
  • 2020-12-29 02:16

    Try this

    yourSelect.find('option').not(':first').remove();

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