如何获取在表中以数组形式选择的Id的复选框

时间:2014-11-13 11:06:32

标签: jquery

我有一个如下所示的表

<table id="sample_1" aria-describedby="sample_1_info">
   <thead>
      <tr>
         <th><input type="checkbox" id="selecctall"></th>
         <th>Status</th>
      </tr>
   </thead>
   <tbody class="odd gradeX">
      <tr>
         <td width="5%"><input type="checkbox" class="checkbox1" id="1"></td>
         <td width="37%">Chips And Chocolates,Bummy Chips,Plain Salted,ytrytr,hyryr</td>
      </tr>
      <tr>
         <td width="5%"><input type="checkbox" class="checkbox1" id="2"></td>
         <td width="37%">Chips And Chocolates</td>
      </tr>
   </tbody>
</table>


       <input type="button" class="btn blue" value="Delete" id="deletebtn">

       $('#selecctall').click(function(event) {  //on click 
if(this.checked) { // check select status
    $('.checkbox1').each(function() { //loop through each checkbox
        this.checked = true;  //select all checkboxes with class "checkbox1"               
    });
}else{
    $('.checkbox1').each(function() { //loop through each checkbox
        this.checked = false; //deselect all checkboxes with class "checkbox1"                       
    });         
}

});

$( "#deletebtn" ).click(function() {
  var $checked = $('#sample_1').find(":checkbox:checked");

      if (!$checked.length) {
        alert('Need to select atlease one checkbox button');
        event.stopImmediatePropagation();
    }

     else {

       // Here 

     }

});

http://jsfiddle.net/tvbucy4y/

4 个答案:

答案 0 :(得分:2)

你可以尝试这个。 DEMO 请参阅控制台。

    $('#deletebtn').click(function() {
        var array = $('#sample_1 input:checked');
        var ids = new Array();
        $.each(array, function(idx, obj) {
            ids.push($(obj).attr('id'));

        });
        console.log(ids);
    });

答案 1 :(得分:2)

试用此代码

var chkIds = $('#sample_1 :checkbox:checked:not(#selecctall)').map(function(i,n) {
    return $(n).attr('id');
}).get().join(',');
    alert(chkIds);

答案已更新:您必须使用:not()排除第一个CheckBox。

答案 2 :(得分:1)

使用此:

else {
     var ids = [];
     $.each($checked, function(i,e){
        console.log(e);
        if ($(e).attr("id") != 'selecctall'){
            ids.push($(e).attr("id"))
        }
 });

答案 3 :(得分:0)

我建议不要费心去获取已检查元素的id,只需使用节点:

$("#deletebtn").click(function () {
    // retrieve a jQuery collection of the checked <input>s from the <tbody>
    // which means we ignore the 'select-all' checkbox):
    var $checked = $('#sample_1 tbody input[type="checkbox"]:checked');

    // if we have any checked elements:
    if ($checked.length) {
        // we find the closest <tr> elements to those checked <inputs>, and
        // remove them:
        $checked.closest('tr').remove();
    } else {
        // otherwise, we alert:
        alert("You need to check at least one checkbox.");
    }

});

JS Fiddle demo

参考文献:

相关问题