如何在使用jquery检查chekbox时创建键值对数组?

时间:2016-06-21 08:01:19

标签: javascript jquery arrays checkbox

我有多个复选框,当我选中一个复选框时,会生成两个键值对。
像这样: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,然后显示一个提示框。

2 个答案:

答案 0 :(得分:1)

您可以查看length复选框的:checked属性。根据您的情况,使用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'/>

答案 1 :(得分:0)

    $("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));
    });