Created
February 21, 2020 13:41
-
-
Save sergejmueller/6d2d891d38d153d7fefec9fbc43e39f1 to your computer and use it in GitHub Desktop.
Radio fields check and uncheck
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
<input type="radio" name="1" class="radio"> | |
<input type="radio" name="1" class="radio"> | |
<input type="radio" name="1" class="radio"> | |
<input type="radio" name="1" class="radio"> | |
<br> | |
<input type="radio" name="2" class="radio"> | |
<input type="radio" name="2" class="radio"> | |
<input type="radio" name="2" class="radio"> | |
<input type="radio" name="2" class="radio"> |
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
document.querySelectorAll('[type=radio]').forEach(item => { | |
item.addEventListener('click', e => { | |
const inputElement = e.target; | |
const inputElementName = inputElement.getAttribute('name'); | |
const previouslyChecked = inputElement.getAttribute('previously-checked'); | |
if (previouslyChecked) { | |
inputElement.checked = false; | |
inputElement.removeAttribute('previously-checked'); | |
} else { | |
const previouslyCheckedElement = document.querySelector('[name="' + inputElementName + '"][previously-checked]'); | |
if (previouslyCheckedElement) { | |
previouslyCheckedElement.removeAttribute('previously-checked'); | |
} | |
inputElement.setAttribute('previously-checked', 1); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment