Fire An Event On Input.checked=true/false _without_ Jquery September 08, 2024 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)"> <buttonid='check'>check</button><buttonid='uncheck'>uncheck</button>document.getElementById('check').onclick = function() { if (!this.checked) { this.click(); } } CopyIf 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/watchExample 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); returntrue; }); CopyFor IE you can use onpropertychangehttp://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'); } }; CopyFor other browsers, you have to poll using setInterval/setTimeoutSolution 2: Have the toggle button actually click the checkbox:<inputtype="checkbox"onchange="alert(this.checked)"><buttononclick="document.getElementsByTagName('input')[0].click()"> toggle </button>CopyIf 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>functiontoggleCB( state ) { var cb = document.getElementById("cb"); arguments.length ? cb.checked = state : cb.click() ; return cb.checked; } </script><inputid="cb"type="checkbox" /><inputtype="button"onClick="alert( toggleCB(true) )"value="Check" /><inputtype="button"onClick="alert( toggleCB(false) )"value="Uncheck" /><inputtype="button"onClick="alert( toggleCB() )"value="Toggle" /> CopyNow 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()<buttononclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].click();">toggle</button>CopySolution 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"