简体   繁体   English

jQuery selectbox删除除两个以外的所有选项(选择器变量名称)

[英]jquery selectbox remove all options except two (selector variable name)

I have the following select box 我有以下选择框

<select name="loc_id_1" id="loc_id_1">
<option value="PLS" selected="selected">-- PLEASE SELECT --</option>
<option value="NEW">-- ADD NEW --</option>
<option value="1">Smith Company</option>
<option value="6">Jones Company</option>
<option value="23">Wright Company</option>
</select>

There are multiple of these on the page loc_id_2, loc_id_3, etc all with different info. loc_id_2,loc_id_3等页面上有多个此类,它们都具有不同的信息。 I am using the following to detect a change in any of them. 我正在使用以下内容来检测其中的任何更改。

$("[id^=loc_id_]").change(function(){
/// my magic code
var lc_id = $(this).attr('id');
my_function(lc_id,data1,data2);
});

This part works great. 这部分效果很好。 The problem I am running into is as part of this code, I call a function that can refresh the data in the changed select box. 我遇到的问题是此代码的一部分,我调用了一个可以刷新更改后的选择框中的数据的函数。 so I use the jquery remove function to refresh the selectbox 所以我用jQuery删除功能刷新选择框

function my_function(id,d,f) {
var sel = $("#" + id);
sel.find('option[value!="NEW"] option[value!="PLS"]').remove();

// ajax code that calls database to append the other entries to the selectbox
}

The problem is, this removes the "ADD NEW" option, but leaves the "PLEASE SELECT" but my options from the database are added just fine. 问题是,这删除了“添加新”选项,但是保留了“请选择”,但是我从数据库中添加的选项就很好了。

Any idea how to fix this... 任何想法如何解决这个问题...

Your selector will look for descendant inside the option element which is having the value NEW.Try, 您的选择会寻找descendant ,其具有的选项元素中value NEW.Try,

sel.find('option[value!="NEW"][value!="PLS"]').remove();

DEMO 演示

You can simply use :gt selector 您可以简单地使用:gt选择器

sel.find('option:gt(1)').remove();

Working Demo 工作演示

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

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