开发者

Remove a certain number of elements from dropdownlist

开发者 https://www.devze.com 2023-02-22 16:57 出处:网络
I have a problem in jQuery. I have a dropdownlist consists of say 10 elements. Now on a checkbox click, I want开发者_运维知识库 to remove first five elements.

I have a problem in jQuery. I have a dropdownlist consists of say 10 elements. Now on a checkbox click, I want开发者_运维知识库 to remove first five elements.

It can be also something like this: I want to remove the elements from index 0 to index 5. How to do that?


This should do what you ask

$('#checkboxID').click(function(){
  $('#dropdownID > option:lt(5)').remove();
});

Demo: http://jsfiddle.net/gaby/VBT42/


If you want to just hide them while the checkbox is checked and show them again on unchecking the checkbox then use

$('#checkboxID').click(function(){
  $('#dropdownID > option:lt(5)').toggle();
});

Demo: http://jsfiddle.net/gaby/VBT42/2/ (will not work for IE though)


And for a universally safe remove/restore use the .detach() docs method and store a reference to the them with the .data() docs method

$('#checkboxID').click(function(){
  if (this.checked) {
       $('#dropdownID').data('removedOptions', $('#dropdownID > option:lt(5)').detach() );
  } else {
      var $dropdown = $('#dropdownID');
      $dropdown.prepend( $dropdown.data('removedOptions') );
  }
});

Demo: http://jsfiddle.net/gaby/VBT42/4/


Try something like this in the checkbox click/change handler:

 $("#selectBox option:lt(5)").remove();


maybe this could work, never tried it myself:

$("option").each(function(index) {
if(index < 5) $(this).remove();
});


adding anyhow

<select name="foo" id="myselect">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
</select>
<input type="checkbox" id="mycheckbox" />

here's the jQuery

$('#mycheckbox').change(function() {
    $("#myselect option:lt(5)").toggle();
    if( $('#myselect option:lt(5)').is(":hidden") ){
        $("#myselect option:eq(5)").attr('selected','selected');
    }else{
        $("#myselect option:eq(0)").attr('selected','selected');
    }
});

here is my fiddle


$("options selector").each(function(i){if(i<5){$(this).remove();}});
0

精彩评论

暂无评论...
验证码 换一张
取 消