简体   繁体   English

我想保留前2个选项,并使用jquery删除select元素中的剩余部分,

[英]I want to keep first 2 options and delete remaining in a select element with jquery,

I want to delete all options in a select element with jquery, except for the first n . 我想用jquery删除select元素中的所有选项,除了前n where n is amount of options to keep . 其中n是要保留的期权数量。

As per your conversation you want that except first 2 option others will be removed. 根据您的对话,您希望除前两个选项外的其他选项都将被删除。 Please try below code it will help you:: 请尝试以下代码,它将为您提供帮助::

Assuming sub_buyer is your selectbox's ID 假设sub_buyer是您的选择框的ID

 $( document ).ready(function() { $('#sub_buyer').find('option').not(':nth-child(1), :nth-child(2)').remove(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="form-control" name="sub_buyer" id="sub_buyer"> <option value="1">FB</option> <option value="2">RM</option> <option value="3">Joey</option> <option value="4">Isaac</option> <option value="5">Christina</option> <option value="6">James</option> <option value="7">Armando</option> <option value="8">Kent</option> <option value="9">Tyler</option> <option value="10">Michael</option> <option value="11">Dylan</option> <option value="12">Ryan</option> <option value="13">John-Ralph</option> <option value="14">John-Mike</option> </select> 

Working jsfiddle url: https://jsfiddle.net/xya0p3ym/ 有效的jsfiddle网址: https ://jsfiddle.net/xya0p3ym/

I can't remember a way to find the last 2 elements of a collection as a selector but this will do it: 我不记得一种找到集合的最后2个元素作为选择器的方法,但这可以做到:

  $('#mySelect') .find('option:last-child') .remove(); $('#mySelect') .find('option:last-child') .remove(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="mySelect"> <option value="">Select one</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> 

function removeLast (a){
var arr = $("#select_id option");
for(var i = 0; i<a;i++){$(arr[arr.length-1]).remove();}
};
removeLast(number_of last_items_to_delete);

This code selects only option tag, not all children and can remove as many last childs as you want. 此代码仅选择选项标签,而不选择所有子项,并且可以根据需要删除最后的子项。

This is working: 这正在工作:

$(document).ready(function(){
  var n = 4;
  var options = $('select').children();

  for (var i = 0; i < options.length; i++) {
    if (i >= n) {
      options[i].remove();
    }
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM