Manish Tiwari Manish Tiwari - 5 months ago 35
jQuery Question

How to make key value pair array when chekbox checked using jquery?

I have multiple checkbox, when i check a checkbox two key value pair will generate.

Like this :

Object {id: "101", name: "example"}



This will generate for every checkbox checked and i want for multiple checkbox checked array. look like this :

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


What I have done

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


When I uncheck checkbox they will be remove from array and want to prevent check maximum 3 checkbox
if >3
then show an alert box.

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