Checkbox Checked in YUI

If you happen to need to trigger an event when a checkbox is checked or unchecked with YUI then this little snippet should help you out.

Just a little heads up. You might be able to get away with no JavaScript by utilising the CSS3 :checked pseudo-class like so:


input[type=checkbox]:checked {
 // Your styles
}

If you need more customisation then this YUI snippet should help.

Making sure you have the current seed file included.


<script src="http://yui.yahooapis.com/3.13.0/build/yui/yui-min.js"></script>

Then add this little block either in an external scripts file or in the footer. All this snippet does is get all checkbox’s and on change checks to see if they return true if the current target is getting checked. If it returns true it will throw an alert and add a class. If not true it it will remove that class.


YUI().use('node', 'event', function (Y) {

  var check = Y.all('.checkbox');
  
  check.on('change', function (e) {
      var checkbox = e.target;
      Y.log(checkbox.get('checked'));
    
    if(checkbox.get('checked')) {
      alert("boom");
      checkbox.addClass('checkbox-checked');
    } else {
      checkbox.removeClass('checkbox-checked');
    }           
 });
  
});

This post currently has no responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

Your email address will not be published. Required fields are marked *

Current ye@r *