Fire An Event On Input.checked=true/false _without_ Jquery May 27, 2023 Post a Comment Consider the following code (http://jsfiddle.net/FW36F/1/): Solution 1: The existing answers work just fine, even with your update. Just be smart about it and don't call click if you don't need to. Also, please don't use inline JS. That was OK 10 years ago. <input type="checkbox" onchange="alert(this.checked)"> <button id='check'>check</button> <button id='uncheck'>uncheck</button> document.getElementById('check').onclick = function() { if (!this.checked) { this.click(); } } Copy If you need to be modified when a script changes the value, in Firefox, you can use https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch Example here http://jsfiddle.net/PPuZ8/ // In FF $ is a shortcut for document.getElementById // It doesn't fire when set from the UI, you have to use a regular handler for that $('cb').watch("checked", function(){ console.log('Checked state changed from script', arguments); return true; }); Copy For IE you can use onpropertychange http://msdn.microsoft.com/en-us/library/ie/ms536956(v=vs.85).aspx (Thanks to jivings for the reminder) Example: http://jsfiddle.net/PPuZ8/1/ document.getElementById('cb').onpropertychange = function() { if (event.propertyName == 'checked') { console.log('Checked state changed onproperty change'); } }; Copy For other browsers, you have to poll using setInterval/setTimeout Solution 2: Have the toggle button actually click the checkbox: <input type="checkbox" onchange="alert(this.checked)"> <button onclick="document.getElementsByTagName('input')[0].click()"> toggle </button> Copy If you wanted any change to the checkbox to inform you of its new position, then I would create a global method for changing the value of the checkbox, and deal with it as a proxy: <script> function toggleCB( state ) { var cb = document.getElementById("cb"); arguments.length ? cb.checked = state : cb.click() ; return cb.checked; } </script> <input id="cb" type="checkbox" /> <input type="button" onClick="alert( toggleCB(true) )" value="Check" /> <input type="button" onClick="alert( toggleCB(false) )" value="Uncheck" /> <input type="button" onClick="alert( toggleCB() )" value="Toggle" /> Copy Now anytime you set or toggle the checkbox, you'll get the checked state back. One last thing, I would avoid using the onClick attribute, and instead bind the click events up from within your JavaScript. Solution 3: Use click() <button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].click();">toggle</button> Copy Solution 4: oninput is the event you need to handle ... https://developer.mozilla.org/en/DOM/DOM_event_reference/input Share Post a Comment for "Fire An Event On Input.checked=true/false _without_ Jquery"
Post a Comment for "Fire An Event On Input.checked=true/false _without_ Jquery"