Javascript – Change/Get check state of CheckBox

htmljavascript

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

Best Answer

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