Created
August 14, 2019 12:08
-
-
Save pedrosancao/48e48b201d0272ec974c67febf42238b to your computer and use it in GitHub Desktop.
enable radio buttons to be unchecked both vanilla and jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// iterate using Array method for compatibility | |
Array.prototype.forEach.call(document.querySelectorAll('[type=radio]'), function(radio) { | |
radio.addEventListener('click', function(){ | |
var self = this; | |
// get all elements with same name but itself and mark them unchecked | |
Array.prototype.filter.call(document.getElementsByName(this.name), function(filterEl) { | |
return self !== filterEl; | |
}).forEach(function(otherEl) { | |
delete otherEl.dataset.check | |
}) | |
// set state based on previous one | |
if (this.dataset.hasOwnProperty('check')) { | |
this.checked = false | |
delete this.dataset.check | |
} else { | |
this.dataset.check = '' | |
} | |
}, false) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment