Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.

JavaScript function

    function checkAddress()     {         if (checkAddress.checked == true)         {             alert("a");         }     } 

HTML

<input type="checkbox" name="checkAddress" onchange="checkAddress()" /> 
like image 920
Stan Avatar asked Apr 04 '11 13:04

Stan


People also ask

How can I change checkbox in state?

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.

Does checkbox have OnClick event?

The CheckBox has been assigned a JavaScript OnClick event handler. When the CheckBox is clicked, the ShowHideDiv JavaScript function is executed. Inside this function, based on whether CheckBox is checked (selected) or unchecked (unselected), the HTML DIV with TextBox is shown or hidden.

How do you readonly a checkbox in HTML?

The readonly attribute can be set to keep a user from changing the value until some other conditions have been met (like selecting a checkbox, etc.). Then, a JavaScript can remove the readonly value, and make the input field editable.


2 Answers

Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.

You also need to pass the checkbox into the function:

function checkAddress(checkbox) {     if (checkbox.checked)     {         alert("a");     } } 

HTML

<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" /> 
like image 138
Tim Down Avatar answered Sep 25 '22 05:09

Tim Down


You need to retrieve the checkbox before using it.

Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.

For example:

function checkAddress() {     var chkBox = document.getElementById('checkAddress');     if (chkBox.checked)     {         // ..     } } 

And your HTML would then look like this:

<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/> 

(Also changed the onchange to onclick. Doesn't work quite well in IE :).

like image 40
Kevin Avatar answered Sep 26 '22 05:09

Kevin