Skip to content

Instantly share code, notes, and snippets.

@pedrosancao
Created August 14, 2019 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrosancao/48e48b201d0272ec974c67febf42238b to your computer and use it in GitHub Desktop.
Save pedrosancao/48e48b201d0272ec974c67febf42238b to your computer and use it in GitHub Desktop.
enable radio buttons to be unchecked both vanilla and jQuery
// 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