我有一个包含重复条目的下拉列表。其中一个重复条目是下拉列表中的选定值。例如:
<select id="country">
<option value="NZ">New Zealand</option> //New Zealand is selected option
<option value="USA">United States</option>
<option value="Ind">India</option>
<option value="NZ">New Zealand</option>
<option value="SA">South Africa</option>
<option value="UK">United Kingdom</option>
<option value="JP">Japan</option>
</select>
现在,我试图删除新西兰选项(重复),但同时,我试图让新西兰的其他条目被选中,以便我将列表视为:
<select id="country">
<option value="USA">United States</option>
<option value="Ind">India</option>
<option value="NZ" selected>New Zealand</option> //removing the duplicate selection.
<option value="SA">South Africa</option>
<option value="UK">United Kingdom</option>
<option value="JP">Japan</option>
</select>
这是用于填充下拉列表的JavaScript:
$.ajax('/url/allcountries', {
method:'GET',
success: function(items){
if(items){
var items = items;
$.each(items, function(i, item) {
$("#country").append($('<option></option>').val(item.code).html(item.name));
//Eg: where item.code = "USA" and item.name ="United States"
if($("#country :selected").text() === item.code){
$("#country :selected").html(item.name);
//Edit as per suggested
var x = {};
$("select[id='country'] > option").each(function () {
if(x[this.text]) {
$(this).remove();
} else {
x[this.text] = this.value;
}
});
//this gives me a duplicate entry at the top of the list.
}
});
} //if condition ends
}//success ends
});
有关如何删除重复项并仅选择它们的任何想法?
答案 0 :(得分:2)
您可以尝试这样:
[].slice.call(country.options)
.map(function(a){
if(this[a.innerText]){
country.removeChild(a);
} else {
this[a.innerText]=1;
}
},{});
<强> JSFIDDLE DEMO 强>
或在Jquery中这样:
var x = {};
$("select[name='country'] > option").each(function () {
if(x[this.text]) {
$(this).remove();
} else {
x[this.text] = this.value;
}
});
答案 1 :(得分:0)
您只需在.each()
之前制作一系列独特商品。这可以通过许多不同的方式完成。这是one way来做这件事。
答案 2 :(得分:0)
在你附加选项element.check之前,如果有另一个元素具有相同的值,那么检查它并移动到下一个选项。
success: function(items){
if(items){
var items = items;
$.each(items, function(i, item) {
if($('option[value='+item.code+']').length!==0){
$('option[value='+item.code+']')[0].selected='true';
return 0;
}
$("#country").append($('<option></option>').val(item.code).html(item.name));
//Eg: where item.code = "USA" and item.name ="United States"
if($("#country :selected").text() === item.code){
$("#country :selected").html(item.name);
//Edit as per suggested
var x = {};
$("select[id='country'] > option").each(function () {
if(x[this.text]) {
$(this).remove();
} else {
x[this.text] = this.value;
}
});
//this gives me a duplicate entry at the top of the list.
}
});
} //if condition ends
}//success ends