Reputation: 567
I am currently working on a project in ASP.NET MVC. I have a page for displaying data where users can use checkboxes to mark different items and then makes changes to those items. On some pages, there are enough checkboxes that a "Select all Checkboxes" button is required. I typed up the code for in javascript and I cannot seem to get it to work no matter what I try. Here is my HTML:
I first loop through my viewmodel data and display a checkbox with an id of my Model's id for each checkbox.
@foreach(var item in Model.Data)
{
<input name="selected" type="checkbox" id="@item.id" value="@item.id"/>
}
Each checkbox displayed on the page now has an ID of each database ID.
I then create this button
<a onclick="selectAll()" class="btn btn-primary">Select All</a>
That button corresponds to this javascript:
<script type="text/javascript" language="javascript">
function selectAll()
{
var stepIDs = @Html.Raw(JsonConvert.SerializeObject(this.Model.Data));
for(let i = 0; i < stepIDs.length; i++)
{
var curr = stepIDs[i].id;
document.getElementById(curr).checked = true;
}
}
</script>
I get the ID's again using the SerializeObject() command and then set each corresponding one to true (dependent upon how many are in the database).
On runtime, the value of the checkbox successfully changes to true, but it does not display a tick in the checkbox. I have also tried using Jquery to try and select it but it does not work either.
Upvotes: 0
Views: 778
Reputation: 1740
You shouldn't use id
s for this kind of functionality.
Instead, give the collection of controls you want to manipulate a class
name.
Then, iterate over the elements with that class
name and perform the actions required.
Here's an example:
One <input type="checkbox" id="chkOne" class="myChecks">
Two <input type="checkbox" id="chkTwo" class="myChecks">
Three <input type="checkbox" id="chkThree" class="myChecks">
<script>
var chk = document.getElementsByClassName("myChecks");
for(var i = 0; i < chk.length; i++) {
chk[i].checked = true;
}
</script>
Upvotes: 0
Reputation: 1337
Try
var curr = stepIDs[i].id;
instead of
var curr = stepIDs[i];
inside the for-loop
Upvotes: 1
Reputation: 49
try
yourCheckBoxVariable.setAttribute("checked","checked");
or
yourCheckBoxVariable.click();
hopefully that helps. what you're doing is a bit out of the scope of my knowledge, but I have dealt with checkboxes not ticking before and both of those solutions above worked for me.
Upvotes: 1