2017-01-12 22 views
3

我在複選框中選中的值應該出現在下拉列表中。如何從<select>下拉列表中刪除現有的<option>?

每次我選擇一個新值時,應該從下拉列表中清除以前的值,並且只應顯示新的選定值。

但是現在,新值將與先前的值一起顯示。

下面是我目前的代碼。

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> 
+0

HTML代碼:<選擇的id = 「選擇客戶」 NAME = 「客戶端」> <選項value =「 - 1」> - select- –

+0

嘗試$('select')。html('');而不是$('select')。empty(); – rahulsm

+0

請添加相關的HTML代碼。 –

回答

0

我假設你在問題中提到的被點擊#clientuser時運行。所以,問題是在功能之間共享的數組selectedKnowledgeBaseArray

無論您何時點擊#clientuserinput[type=checkbox]:checked選擇器的選中元素都附加在selectedKnowledgeBaseArray之後,然後將此數組傳遞給AJAX調用。

我不確定AJAX調用返回的是什麼,但是如果它返回已通過的元素,函數buildSortedData將接收它們並嘗試使用select.add(option, i + 1);將它們附加到您的選擇框。

另外注意,我們在調用下面的代碼片段中環

$('.deleteMeetingClose').on("click", function() { 
    var select = document.getElementById("select-client"); 
    $('select').empty(); 
}); 

這結合對.deleteMeetingClose相匹配的所有元素的多個點擊事件,如果沒有,這將在未來創造的問題是肯定的。

+0

它有什麼解決方案? –

+0

@KomalJain解決方案是什麼? – 31piy

0

給在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() 

這段代碼有幫助我,希望它可以幫助你

0

嘗試$(select).empty();而不是$('select')。empty();

代替或者:

var select = document.getElementById("select-client"); 
$('select').empty(); 

你可以使用jQuery選擇:

$("#select-client").empty(); 
相關問題