Looping through a datatable using JQuery

Viewed 20

Hi I'm very new to Javascript, when I click a button I want to loop through my datatable looking for checkbox values of true, when a true value is found I want to pass the Id from the row and text from an input field to a method in my controller as parameters.

I've been trying something like this (Javascript Code below) but I just can't get it working and I have no idea if my loop function is running. Could someone please help me figure this out?

HTML for button

<form method="post" style="margin-bottom: 41px">
    <input class="btn btn-primary text-warning" value="Extend Selected Licenses" type="submit" onclick="loopGrid" id="btnExtendSelectedLicense"></input>
    <input class="form-control" id="NumberOfDaysExtended" type="number" style="height: 30px; width: 100px; margin-left: 216px; margin-top: -41px">
</form>

HTML for checkbox

<td> 
    <input class="form-check-input bg-light" id="SelectedLicenses" type="checkbox">
</td>

JQuery script for loop function

function loopGrid {
    var table = document.getElementById("CustomerLicensingTable");
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {
            SelectedLicenses == true
            //call method
            console.log("found a true value")
        } else {
                tr[i].style.display = "none";
            }
        }
    }
}
1 Answers

Here is how you can do it

 
    function loopGrid() {
        var $table = $("#CustomerLicensingTable tr");
        $table.each(function(){
           var $check = $($(this).find(".form-check-input"));
           if($check.is(':checked')){
              console.log('Checked');
              $(this).show();
           } else {
             console.log('Not checked');
              $(this).hide();
           }
        });
    }
    $(document).on("click", function(e){
       e.preventDefault();
       loopGrid();
       //$("#license-form").submit();
       // OR use Ajax 
    });
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form method="post" style="margin-bottom: 41px" id="license-form">
    <input class="btn btn-primary text-warning" value="Extend Selected Licenses" type="button" id="btnExtendSelectedLicense"></input>
    <input class="form-control" id="NumberOfDaysExtended" type="number" style="height: 30px; width: 100px; margin-left: 216px; margin-top: -41px">
</form>

<table id="CustomerLicensingTable">
  <tr>
    <td>
      <input class="form-check-input bg-light" type="checkbox">
    </td>
  </tr>
  <tr>
    <td>
      <input class="form-check-input bg-light" type="checkbox">
    </td>
  </tr>
  <tr>
    <td>
      <input class="form-check-input bg-light" type="checkbox" checked="checked">
    </td>
  </tr>
  <tr>
    <td>
      <input class="form-check-input bg-light" type="checkbox">
    </td>
  </tr>
</table>

Related