Skip to content Skip to sidebar Skip to footer

Fire An Event On Input.checked=true/false _without_ Jquery

Consider the following code (http://jsfiddle.net/FW36F/1/):

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);
   returntrue;
});

For 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');    
    }
};

For other browsers, you have to poll using setInterval/setTimeout

Solution 2:

Have the toggle button actually click the checkbox:

<inputtype="checkbox"onchange="alert(this.checked)"><buttononclick="document.getElementsByTagName('input')[0].click()">
  toggle
</button>

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>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" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

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

<buttononclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].click();">toggle</button>

Solution 4:

oninput is the event you need to handle ... https://developer.mozilla.org/en/DOM/DOM_event_reference/input

Post a Comment for "Fire An Event On Input.checked=true/false _without_ Jquery"