JSFiddle - React, Tailwind, and code Playground
HTML
<label for="checkboxtest" id="lbl">This is a label</label><input type="checkbox" id="checkboxtest">
JavaScript
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();
}
};
});
}
var checkbox = $('#checkboxtest');
var label = $('#lbl');
function switcheroo() {
checkbox.val(true);
label.text('checbox checked = '+checkbox.val());
...