How can we make a checkbox checked or unchecked programatically based on the value? That is to say, for a particular user if the value is true, the checkbox should be checked, else if the value is false the checkbox needs to be unchecked. I declared the checkbox in the following way:
<input type="checkbox" class="checkbox">
Add checked = "checked" to the input you want selected. For XHTML the recommended way is as described. Check HTML manual and W3C to confirm. The markup posted isn't XHTML, so it's logical to use just the simple keyword attribute checked .
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
attr("checked","checked"); To uncheck the checkbox: $("#checkboxid").
If you do not want to use @Html.CheckBoxFor for whatever reason and you'd like to stick to
<input type="checkbox">
then this is what I found to be the best way to do it:
<input @(Convert.ToBoolean(Model.YourPropertyHere) == true ? "checked='checked'" : string.Empty) type="checkbox" />
The code that @Yasser provided above:
checked="@(required ? "checked" : "")"
Did not work for me because it was still adding the checked attribute to the element, and setting checked="" will still render the check box as checked, which was not the desired output, instead if you wrap the whole statement into a razor block like so:
@(Convert.ToBoolean(Model.YourPropertyHere) == true ? "checked='checked'" : string.Empty)
you will get the desired results.
if(condition = true)
{
@Html.CheckBoxFor(x => x.Test, new { @checked = "checked" })
}
else
{
@Html.CheckBoxFor(x => x.Test)
}
Hope this helps :)
There is a simpler way to include or not include the checked
attribute if you are writing our your own <input>
instead of using alternatives such as Html.CheckBoxFor
:
<input type="checkbox" checked="@isChecked">
Razor is smart enough to automatically generate either
<input type="checkbox" checked="checked">
or
<input type="checkbox">
depending on whether isChecked
is true
or false
. No need for if statements or duplicate code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With