Change/Get check state of CheckBox

JavascriptHtml

Javascript Problem Overview


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()" />

Javascript Solutions


Solution 1 - Javascript

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)" />

Solution 2 - Javascript

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 :).

Solution 3 - Javascript

I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.

function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.

    if(document.getElementById(from).checked==true) 
    //checks status of "from" element. change to whatever validation you prefer.
	    {
	    	document.getElementById(to).checked=true;
             //if validation returns true, checks target checkbox
	    }
    else
	    {	
	    	document.getElementById(to).checked=false; 
             //if validation returns true, unchecks target checkbox
	    }
}

HTML being something like

<input type="radio" name="bob" onclick="copycheck('from','to');" />

where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to". As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.

Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.

Hope this helps.

Solution 4 - Javascript

You need this:

window.onload = function(){
	var elCheckBox=document.getElementById("cbxTodos");
	elCheckBox.onchange =function (){
		alert("como ves");
	}
};

Solution 5 - Javascript

Needs to be:

if (document.forms[0].elements["checkAddress"].checked == true)

Assuming you have one form, otherwise use the form name.

As a side note, don't call the element and the function in the same name it can cause weird conflicts.

Solution 6 - Javascript

I know this is late info, but in jQuery, using .checked is possible and easy! If your element is something like:

<td>
    <input type="radio" name="bob" />
</td>

You can easily get/set checked state as such:

$("td").each(function()
{
    $(this).click(function()
    {
        var thisInput  = $(this).find("input[type=radio]");
        var checked = thisInput.is(":checked");
        thisInput[0].checked = (checked) ?  false : true;
    }
});

The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object! ENJOY!

Solution 7 - Javascript

<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />

Solution 8 - Javascript

This is an example of how I use this kind of thing:

HTML :

<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">

JAVASCRIPT :

function ThisIsTheFunction(temp,temp2) {
  if(temp2 == true) {
	document.getElementById(temp).style.visibility = "visible";
  } else {
	document.getElementById(temp).style.visibility = "hidden";
  }
}

Solution 9 - Javascript

var val = $("#checkboxId").is(":checked");

Solution 10 - Javascript

Here is a quick implementation with samples:

Checkbox to check all items:

<input id="btnSelectAll" type="checkbox">

Single item (for table row):

<input class="single-item" name="item[]" type="checkbox">

Js code for jQuery:

$(document).on('click', '#btnSelectAll', function(state) {
    if ($('#btnSelectAll').is(':checked')) {
        $('.single-item').prop('checked', true);
        $('.batch-erase').addClass('d-block');
    } else {
        $('.single-item').prop('checked', false);
        $('.batch-erase').removeClass('d-block');
    }
});

Batch delete item:

<div class="batch-erase d-none">
	<a href="/path/to/delete" class="btn btn-danger btn-sm">
		<i class="fe-trash"></i> Delete All
	</a>
</div>

Solution 11 - Javascript

This will be useful

$("input[type=checkbox]").change((e)=>{ 
  console.log(e.target.checked);
});
 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStanView Question on Stackoverflow
Solution 1 - JavascriptTim DownView Answer on Stackoverflow
Solution 2 - JavascriptKevinView Answer on Stackoverflow
Solution 3 - JavascriptPedro SousaView Answer on Stackoverflow
Solution 4 - JavascriptAarónView Answer on Stackoverflow
Solution 5 - JavascriptShadow Wizard Says No More WarView Answer on Stackoverflow
Solution 6 - JavascriptSpYk3HHView Answer on Stackoverflow
Solution 7 - Javascriptitzmukeshy7View Answer on Stackoverflow
Solution 8 - JavascriptcaptainpoopView Answer on Stackoverflow
Solution 9 - JavascriptRamya Prakash RoutView Answer on Stackoverflow
Solution 10 - JavascriptSinan EldemView Answer on Stackoverflow
Solution 11 - Javascriptdaryosh setorgView Answer on Stackoverflow