64

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()" />
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Stan
  • 25,744
  • 53
  • 164
  • 242

11 Answers11

97

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)" />
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 2
    I don't think his issue is the type of event: as you mentioned onchange is more inclusive than onclick anyway. The issue is that there's no object called `checkAddress` with a `checked` property. Most likely, `checkAddress` is the going to resolve as the function itself, since it's also named that. Just giving something a name attribute in HTML doesn't create a variable named that in Javascript. Passing 'this' in, or any of the options in the answers below should do the trick. – brianmearns Apr 27 '12 at 19:14
  • @bmearns: I think I failed to spot the presumably-undeclared variable (that clashes with the function name) in my indecent haste to be first, so I concede you're probably right. Surprised this was accepted. – Tim Down Apr 27 '12 at 21:38
  • 2
    For those using a framework like React that binds the Application context to "this" in the callback, you should use `checkbox.target.checked` instead of `checkbox.checked` – user3188040 Jun 13 '17 at 08:20
  • This is what I was looking for, but I do find it odd that "onclick" can work with keyboard events. – Jeremy Trpka Jun 12 '20 at 12:56
22

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

Community
  • 1
  • 1
Kevin
  • 5,626
  • 3
  • 28
  • 41
9

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.

Pedro Sousa
  • 99
  • 1
  • 3
  • 5
    You could reduce that to `document.getElementById(to).checked = document.getElementById(from).checked;`. – Tim Down Aug 20 '13 at 13:28
4

You need this:

window.onload = function(){
    var elCheckBox=document.getElementById("cbxTodos");
    elCheckBox.onchange =function (){
        alert("como ves");
    }
};
Aarón
  • 41
  • 1
3
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
itzmukeshy7
  • 2,669
  • 1
  • 21
  • 29
3

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.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
2

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!

SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
0

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";
  }
}
0

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

0

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>
Sinan Eldem
  • 5,564
  • 3
  • 36
  • 37
-1

This will be useful

$("input[type=checkbox]").change((e)=>{ 
  console.log(e.target.checked);
});
Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
daryosh setorg
  • 120
  • 1
  • 9