简体   繁体   中英

How should I iterate this loop through the table columns to get the id

I was trying to fetch all the records checked and get the ids of those. but the code using foreach does not iterates. It fetches me only the first row id. Here is my code below

$("#saveToDocReg").click(function () {
    var just = $("#registerGrid").find("tr").find("td");
    $("#registerGrid").find("tr").find("td").each(function () {
        if ($(this).find("input:checkbox").is(':checked')) {
            var ids = $(this).find("input:hidden").val();
            alert(ids);
            var allIds = [];

            for (var x = 0, l = ids.length; x < l; x++) {
                allIds.push(ids[x].value);
            }

            var str = allIds.join(', ');
        }
    });
});

And once I get the ids how am I supposed to get it controller. I was facing these issues. Can anyone give me some suggestions?

Your allIds and related logic are inside your loop iterator function, so they're recreated every time the loop iterator function is called (eg, for each td ).

If your goal is to get all the IDs (values from the hidden fields), then it can be a lot simpler than that:

$("#saveToDocReg").click(function () {
    var allIds = $("#registerGrid tr td:has(input:checkbox:checked)").map(function() {
        return $(this).find("input:hidden").val();
    }).get();
    alert(allIds.join(', '));
});

Changes:

  1. The primary change is getting allIds outside the loop

  2. $("#registerGrid").find("tr").find("td") can be written using descendant selectors instead: $("#registerGrid tr td")

  3. Instead of looping through all the td s, we only need to loop through ones that have a checked checkbox. We can use :has with jQuery's pseudo :checked selector.

  4. jQuery objects have a map function that builds a jQuery object from what you return from each call to a callback; you can then get the underlying array from it using .get()

Live Example:

 $("#saveToDocReg").click(function() { var allIds = $("#registerGrid tr td:has(input:checkbox:checked)").map(function() { return $(this).find("input:hidden").val(); }).get(); alert(allIds.join(', ')); }); 
 <input type="button" id="saveToDocReg" value="Click Me"> <table id="registerGrid"> <tbody> <tr> <td> <input type="checkbox" checked> <input type="hidden" value="1"> </td> </tr> <tr> <td> <input type="checkbox"> <input type="hidden" value="2"> </td> </tr> <tr> <td> <input type="checkbox" checked> <input type="hidden" value="3"> </td> </tr> <tr> <td> <input type="checkbox"> <input type="hidden" value="4"> </td> </tr> </tbody> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM