Javascript 如何从下拉列表中删除现有的?

Javascript 如何从下拉列表中删除现有的?,javascript,jquery,Javascript,Jquery,我在复选框中选中的值应显示在下拉列表中 每次我选择一个新值时,应该从下拉列表中清除以前的值,并且只显示新选择的值 但现在,新值将与以前的值一起显示 下面是我目前拥有的代码 HTML: JavaScript: <script> $(document).ready(function() { var selectedKnowledgeBaseArray = []; $("#clientuser").on('click', function() { $("input[t

我在复选框中选中的值应显示在下拉列表中

每次我选择一个新值时,应该从下拉列表中清除以前的值,并且只显示新选择的值

但现在,新值将与以前的值一起显示

下面是我目前拥有的代码

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中为select选项指定一个ID或类名,如下面的代码所示

<select id="select-choice">
</select>

这段代码对我有帮助,希望它能帮助你

我假设你在问题中提到的内容是在点击clientuser时运行的。因此,问题在于函数之间共享的数组selectedKnowledgeBaseArray

无论何时单击clientuser,input[type=checkbox]:checked selector的选中元素都会附加到selectedKnowledgeBaseArray中,然后将该数组传递给AJAX调用

我不确定AJAX调用返回什么,但是如果它返回您传递的元素,函数buildSortedData将接收它们,并尝试使用select.addoption,I+1;将它们附加到您的选择框中

还要注意,您正在循环中调用以下代码段

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

这将绑定与.deleteMeetingClose匹配的所有元素上的多个单击事件,如果尚未绑定,这肯定会在将来产生问题。

请尝试$select.empty;而不是$'select'。空

或者代替:

var select = document.getElementById("select-client");
$('select').empty();
您可以使用jquery选择器:

$("#select-client").empty();

html代码是:-select-try$'select'.html;而不是$'select'。空;请添加相关的HTML代码。解决方案是什么?@KomalJain解决方案是什么?
var select = document.getElementById("select-client");
$('select').empty();
$("#select-client").empty();