Simple jQuery plugin to make checkbox values readable/settable by $(checkbox).val() isnstead of attr

If you put this little script in your document after jQuery has loaded you can simply read the values of a checkbox with $('#checkboxid').val() and set it with val.

 I added comments to explain what line of code does what.

I hope this makes your life a little bit easier.


 To have a live example to fiddle with, check out http://jsfiddle.net/e3q8cmum/



if(typeof window['$'] !== 'undefined' || typeof window['jQuery'] !== 'undefined') {
 jQuery(function(){
  // Saving the old instance so this can do stuff when we don't need it.
  jQuery.fn.ZAGREUSoldoldoldVal = jQuery.fn.val;
  // Making our own value function!
  jQuery.fn.val = function(value){
   // Check if it's  a checkbox. If so, do our magic!
   if(typeof value !== 'undefined' && (this[0] instanceof HTMLInputElement && this[0].getAttribute('type') == 'checkbox')) {
    // Saving our instance for scoping
    var that = this;
    // Generic setvalue function to prevent code duplication.
    var setval = function(bool) {
     var oldbool = that[0].checked;
     that[0].checked = bool;
     // Remove this if you don't want a trigger whent he value changes.
     if(oldbool !== bool) {
      that.trigger('change');
     }
    }
    // All possible values that can be entered. False means unchecked, true means checked.
    // Modify as needed.
    switch(value) {
     case 'j' : setval(true);break;
     case 'y' : setval(true); break;
     case 'n' : setval(false); break;
     case true : setval(true);break;
     case false : setval(false);break;
     case 1 : setval(true);break;
     case 0 : setval(false);break;
     case 'checked' : setval(true);break;
     case '' : setval(false);break;
    } 
   }
   // We didn't get an argument, so we assume we want to read the data
   else if(typeof value === 'undefined' && (this[0] instanceof HTMLInputElement && this[0].getAttribute('type') == 'checkbox')) {
    return this[0].checked// ? 'y' : 'n';//<-- optional string return... depends on what you want
   }
   else{
    // Default handling of the val function.
    return typeof value !== 'undefined' ? jQuery(this).ZAGREUSoldoldoldVal(value) : jQuery(this).ZAGREUSoldoldoldVal();
   }
  }; 
 });
}

Comments

Popular Posts