Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a checkbox checked or unchecked based on the value?

Tags:

c#

asp.net-mvc

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">
like image 823
always v Avatar asked Aug 07 '12 05:08

always v


People also ask

How do I make a checkbox automatically checked?

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 .

How do you check if a checkbox is checked or unchecked?

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.

How do you make a checkbox unchecked in HTML?

attr("checked","checked"); To uncheck the checkbox: $("#checkboxid").


3 Answers

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.

like image 101
ranah Avatar answered Oct 19 '22 12:10

ranah


if(condition = true)
{
@Html.CheckBoxFor(x => x.Test, new { @checked = "checked" })
}
else
{
@Html.CheckBoxFor(x => x.Test)
}

Hope this helps :)

like image 25
Yasser Shaikh Avatar answered Oct 19 '22 14:10

Yasser Shaikh


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.

like image 18
DavGarcia Avatar answered Oct 19 '22 12:10

DavGarcia