[英]How to remove existing <option> from a <select> dropdown list?
我在復選框中選中的值應顯示在下拉列表中。
每次選擇新值時,都應從下拉列表中清除以前的值,並且只顯示新選擇的值。
但現在,新值與先前的值一起顯示。
以下是我目前的代碼。
HTML:
<html>
<body>
<select id="select-client" name="client">
<option value="-1">-select-</option>
</select>
</body>
</html>
JavaScript的:
<script>
$(document).ready(function() {
var selectedKnowledgeBaseArray = [];
$("#clientuser").on('click', function() {
$("input[type=checkbox]:checked").each(function() {
alert($(this).val());
selectedKnowledgeBaseArray.push($(this).val());
});
$.ajax({
method: "POST",
url: "client_user_map.json",
processData: true,
data: {
selectedKnowledgeBaseArray: selectedKnowledgeBaseArray
},
traditional: true,
dataType: "json",
success: function(data) {
$("#clntusrmap").show();
$('#clntusrmap').find('input:text').val('');
$('input:checkbox').removeAttr('checked');
buildSortedData(data);
}
});
function buildSortedData(data) {
if (data[0].length > 0) {
var select = document.getElementById("select-client");
for (var i = 0; i < data[0].length; i++) {
var option = document.createElement('option');
option.text = option.value = data[0][i];
console.log(data[0][i]);
select.add(option, i + 1);
$('.deleteMeetingClose').on("click", function() {
var select = document.getElementById("select-client");
$('select').empty();
});
}
}
}
});
});
</script>
在html中為您的選擇選項提供ID或類名,如下面的代碼所示
<select id="select-choice">
</select>
並在jQuery寫
/*if it is given an id*/
$('#select-choice").empty()
/*else if it is given a class name then*/
$('.select-choice').empty()
這段代碼對我有所幫助,希望它對你有幫助
我假設你在問題中提到的是在點擊#clientuser
時運行的。 所以,問題是在函數之間共享的數組selectedKnowledgeBaseArray
。
無論何時單擊#clientuser
, input[type=checkbox]:checked
的checked元素都會附加在selectedKnowledgeBaseArray
,然后將此數組傳遞給AJAX調用。
我不確定AJAX調用返回什么,但如果它返回你傳遞的元素,函數buildSortedData
將接收它們並嘗試使用select.add(option, i + 1);
將它們附加到您的選擇框中select.add(option, i + 1);
。
還要注意你在循環中調用以下代碼段
$('.deleteMeetingClose').on("click", function() {
var select = document.getElementById("select-client");
$('select').empty();
});
這會綁定.deleteMeetingClose
匹配的所有元素上的多個單擊事件,如果還沒有,這將在將來確定會產生問題。
嘗試$(select).empty(); 而不是$('select')。empty();
或者代替:
var select = document.getElementById("select-client");
$('select').empty();
你可以使用jquery選擇器:
$("#select-client").empty();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.