【问题标题】:How to make key value pair array when chekbox checked using jquery?使用jquery检查复选框时如何制作键值对数组?
【发布时间】:2016-10-22 15:57:34
【问题描述】:

我有多个复选框,当我选中一个复选框时,将生成两个键值对。
像这样:Object {id: "101", name: "example"}

这将为每个选中的复选框生成,我想要多个复选框选中的数组。看起来像这样:

[{id:"id1",name:"name1"},{id:"id2",name:"name2"}]

我做了什么

$('.chkCompare').click(function(event) {
    var value = [],
        projectName = {},
        span = $(this).attr('id'),
        value = $('.chkCompare:checked').map(function() {
            $('#span' + span).text('ADDED').css({
                "color": "green"
            });
            projectName['id'] = $(this).attr('id');
            projectName['name'] = $(this).attr('title');
            return value.push(projectName);
        }).get();
});

当我取消选中复选框时,它们将从数组中删除并希望阻止选中最多 3 个复选框 if >3 然后显示一个警告框。

【问题讨论】:

  • 你能用你当前的代码添加 jsfiddle.net 链接吗?
  • 不要试图“从数组中删除”——每次都从:checked的列表中重建数组

标签: javascript jquery arrays checkbox


【解决方案1】:

您可以检查:checked 复选框的length 属性。根据您的情况并使用event.preventDefault() 取消默认操作。

$('.chkCompare').click(function(event) {
  var checkedElemets = $('.chkCompare:checked');
  if (checkedElemets.length > 3) {
    event.preventDefault();
    alert('Only 3 checkbox can be checked');
  }

  var values = checkedElemets.map(function() {
    return {
      id: this.id,
      name: this.title
    };
  }).get();

  console.log(values)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="chkCompare" title='t1' id='i1' />
<input type="checkbox" class="chkCompare" title='t2' id='i2'/>
<input type="checkbox" class="chkCompare" title='t3' id='i3'/>
<input type="checkbox" class="chkCompare" title='t4' id='i4'/>
<input type="checkbox" class="chkCompare" title='t5' id='i5'/>

【讨论】:

    【解决方案2】:
        $("input[type='checkbox']").change(function(){
          var arr = {};
           var count = 0;
          $.each($("input[type='checkbox']:checked"), function(){            
             if(count++<3){
               arr[this.id] =this.name;
             }else{
               $(this).prop('checked', false);
             }
    
          });
          console.log(JSON.stringify(arr));
        });
    

    【讨论】:

      猜你喜欢
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      相关资源
      最近更新 更多