I have a checkbox on a form which is unchecked by default as usual. Now I want to perform two separated actions on the checked and unchecked state of this checkbox.
This is my checkbox:
<form> syn<input type="checkbox" name="checkfield" id="g01-01" onchange="doalert(this.id)"/> </form>
And this is my script:
function doalert(id){ if(this.checked) { alert('checked'); }else{ alert('unchecked'); } }
It just alerts unchecked! What is the best way to do this?
Checking if a checkbox is checked 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.
attr("checked","checked"); To uncheck the checkbox: $("#checkboxid").
Checkbox event handling using pure Javascript There are two events that you can attach to the checkbox to be fired once the checkbox value has been changed they are the onclick and the onchange events.
The <input type="checkbox"> defines a checkbox. The checkbox is shown as a square box that is ticked (checked) when activated. Checkboxes are used to let a user select one or more options of a limited number of choices. Tip: Always add the <label> tag for best accessibility practices!
We can do this using JavaScript, no need of jQuery. Just pass the changed element and let JavaScript handle it.
HTML
<form id="myform"> syn<input type="checkbox" name="checkfield" id="g01-01" onchange="doalert(this)"/> </form>
JS
function doalert(checkboxElem) { if (checkboxElem.checked) { alert ("hi"); } else { alert ("bye"); } }
Demo Here
The problem is how you've attached the listener:
<input type="checkbox" ... onchange="doalert(this.id)">
Inline listeners are effectively wrapped in a function which is called with the element as this. That function then calls the doalert function, but doesn't set its this so it will default to the global object (window in a browser).
Since the window object doesn't have a checked property, this.checked
always resolves to false.
If you want this within doalert to be the element, attach the listener using addEventListener:
window.onload = function() { var input = document.querySelector('#g01-01'); if (input) { input.addEventListener('change', doalert, false); } }
Or if you wish to use an inline listener:
<input type="checkbox" ... onchange="doalert.call(this, this.id)">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With