Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default checkbox status with javascript?

I am used to doing this in jQuery

$('#RememberMe').attr('checked', true); 

but I can't remember how to do it in Javascript I thought that

document.getElementById("RememberMe").value = "True"; 

would work, but it doesn't, it changes the value but does not create the visual check on the html.

I am trying to set the checkbox to on by default. here is the html

<input id="RememberMe" name="RememberMe" type="checkbox" value="false" />   
like image 317
Astronaut Avatar asked May 03 '12 17:05

Astronaut


People also ask

What is the way to get the status of a checkbox in JavaScript?

To get the state of a checkbox, you follow these steps: 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.

What is the default value of checkbox?

The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.

How do I make a checkbox always checked in HTML?

The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.


1 Answers

To change checkbox state try this:

document.getElementById("RememberMe").checked = true;

If you need to change the value of checkbox as an input element use:

document.getElementById("RememberMe").value = "New Value";

However, you can set default value and state in HTML markup:

<input id="RememberMe" name="RememberMe" type="checkbox" value="The Value" checked="checked" /> 
like image 51
VisioN Avatar answered Sep 19 '22 23:09

VisioN