【问题标题】:select and unselect from a dropdown list从下拉列表中选择和取消选择
【发布时间】:2014-11-25 18:13:19
【问题描述】:

在多选 jquery 下拉列表中,我希望如果一个项目被选中,它会进入一个数组,如果一个项目未被选中,它会从该数组中删除。我做到了:

var optionValues = [];
$("#myselect").change(function() {
    $("select option:selected").each(function() {
        optionValues.push($(this).val());
    });

    $('select option:not(:selected)').each(function() {
        itemtoRemove = $(this).val();
        optionValues.splice($.inArray(itemtoRemove, optionValues), 1);
    });
    $('#this').val(optionValues.join());
}).trigger( "change" ); 
<input type="text" id="this">

但它在文本框中没有显示任何内容。有什么想法吗?

【问题讨论】:

  • 您在每个循环的第二个中从数组中删除所有内容,因此它始终为空

标签: javascript jquery jquery-multiselect


【解决方案1】:

使用map() 创建您的数组并在每次更改时创建一个全新的数组要容易得多,因此您不必费心寻找要删除的数组的特定元素。试试这个:

var optionValues = [];
$('#myselect').change(function() {
    optionValues = $('option:selected', this).map(function() {
        return this.value;
    }).get();
    $('#this').val(optionValues.join());
}).trigger('change');

Example fiddle

【讨论】:

  • 我想取消选择它从数组中删除
  • 这段代码就是这样做的。检查小提琴以进行演示。
  • 太好了。非常感谢! 8分钟后我会接受的
【解决方案2】:

问题是您没有检查$.inArray(itemtoRemove, optionValues) 调用的返回。

$('select option:not(:selected)').each(function() {
        itemtoRemove = $(this).val();
        var index = $.inArray(itemtoRemove, optionValues);
        if(index != -1) {
            optionValues.splice(index,1);
        }
 });

http://jsfiddle.net/00shke8a/

【讨论】:

    【解决方案3】:
    $("#myselect").change(function() {
    var optionValues = [];
    $("select option:selected").each(function() {
        optionValues.push($(this).val());
      });
    
     $('#this').val(optionValues.join());
    }).trigger( "change" ); 
    

    http://jsbin.com/gejigucimo/1/edit

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-17
      • 2017-05-19
      • 2021-08-26
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      相关资源
      最近更新 更多