2016-06-21 54 views
0

我有多個複選框,當我檢查一個複選框將生成兩個關鍵值對。
像這樣的:Object {id: "101", name: "example"}

這將生成每個複選框選中,我想多個複選框選中陣列。是這樣的:如何使用jquery進行chekbox檢查時創建鍵值對數組?

[{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然後顯示一個警告框。

+0

可以添加你當前的代碼jsfiddle.net鏈接? – RomanPerekhrest

+0

不要試圖「從數組中刪除」 - 每次從':checked'列表重建數組 –

回答

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)); 
    }); 
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'/>

相關問題