从行中的复选框获取表值

Getting table values from checkbox in rows

本文关键字:获取 复选框      更新时间:2023-09-26

我正在做这个演示。如何在JS数组或Object中推送选中行的值?

var obj=[
    {
        id : "001",
        name : "apple",
        category : "fruit",
        color : "red"
    },
    {
        id : "002",
        name : "melon",
        category : "fruit",
        color : "green"
    },
    {
        id : "003",
        name : "banana",
        category : "fruit",
        color : "yellow"
    }
]
$.each(obj, function (index, item) {
     var eachrow = "<tr>"
                 + "<td id="+index+"><input type='checkbox'></td>"
                 + "<td>" + item["id"] + "</td>"
                 + "<td>" + item["name"] + "</td>"
                 + "<td>" + item["category"] + "</td>"
                 + "<td>" + item["color"] + "</td>"
                 + "</tr>";
     $('#tbody').append(eachrow);
});

试试这个,

现场演示

单击"获取行"按钮后,您将获得所需的输出。

$("#btn").on("click",function(){
    var checkedRows = [];
    $("#tbody tr").each(function(){
        if($(this).find("input").is(":checked")){
            checkedRows.push($(this).find("td:eq(1)").html());
        }    
        console.log(checkedRows);    
    });
    var result = [];
    $.each(obj,function(item){
        if(checkedRows.indexOf(item.id)>-1)
       result.push(item) ;
    });   
      console.log(result);    
});

如果我理解正确,你可以尝试这样的方法:

$(function(){
  $('input[type="checkbox"]').on('change', function(){
    data.push($(this).parent().attr('id'));
  });
});

此处更新了fiddle