Populate checkbox in rows based on Model Object Variable
Populate checkbox in rows based on Model Object Variable
Hi,
I'm displaying checkboxes in column in my table and I would like to populate the checkboxes based on a variable associated with each item in Model.SearchResult, e.g. @item.Status in the DB might be 0,1, true, false etc.
How can I do a logical comparison for each row's checkbox to check the value and checking it accordingly? I know I can select all of the checkboxes in JS using
$("#selectAll").on("change", function () {
table.$("input[type='checkbox']").attr('checked', $(this).is(":checked"));
console.log($('selectAll').val());
});
And similarly, I know how to wait for an individual checkbox's click event but I need the JS to run for every row's checkbox before any click events, which I'm not entirely sure how to do.
Currently I'm displaying the checkboxes as such in my html
<table class="table-responsive table-striped compact table-hover" data-toggle="bootstrap-table" data-single-select="true" data-click-to-select="true" id="statsTable" style="width: 100%">
<thead>
<tr class="table-headers">
<th>ID</th>
<th>Name</th>
<th>Enable All <input type="checkbox" id="selectAll"/></th>
<th>Data</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.SearchResult)
{
<tr>
<td "col-md-1" class="ID" val="@item.ID">@item.ID</td>
<td "col-md-1" val="@item.Name">@item.Name</td>
<td><input type="checkbox" class="checkBox"/></td>
<td></td>
</tr>
}
</tbody>
</table>
Thank you for time and assistance.
Answers
Hi @LearningStuff ,
I don't follow your thread but this might help - it's showing how to count checkboxes in a column - I suspect you can use this as a template for your requirements.
Cheers,
Colin
Hi @colin
Sorry for any confusion, let me clarify.
Essentially I would like certain checkboxes showing checked if a value in the database for each object is 1. I tried to achieve this via Razor in my cshtml by doing
However, this keeps the checkbox click event only returning true even when unchecking.
I handle the checkbox event in my js file as suggested in the other thread
With the code above, checkbox returns true/false accurately on click/unclick, but when I add in the Razor code into my cshtml, it only returns true despite unclick.
@colin Thanks for showing me the every method. I'm about to select all checkboxes using that however, I come across the same issue as it's constantly running it but I only want it to run once. Even on unclick, it shows true for the checkboxes because the function is constantly running? I'm not entirely sure.
Here is my js
Here is how I solved the issue, I had to use js to get the checkbox value instead of jQuery. See the status variable in the js file.
cshtml
js