HTML - How in simple way to make input radio element deselect on next click?
As in the question, I am looking for a simple way to deselect <input type="radio" /> button on next click.
Is there simple solution?
You should use JavaScript to get that effect.
e.g.:
// ONLINE-RUNNER:browser;
<label>
<input id="my-input" type="radio" />
<span>Some label ...</span>
</label>
<script>
function findTarget(input) {
const labels = input.labels;
if (labels && labels.length > 0) {
return labels[0];
}
return input;
}
function addOnBeforeClick(input, callback) {
const target = findTarget(input);
let pointer = false; // mouse and touch gestures
target.addEventListener('mousedown', function(e) {
if (e.button === 0) {
pointer = true;
}
});
target.addEventListener('mouseup', function(e) {
if (pointer) {
callback(e);
}
});
window.addEventListener('mouseup', function(e) {
pointer = false;
});
if (input.type === 'radio' || input.type === 'checkbox') {
let key = false; // key gestures (when input is focused space selects/deselects checkbox/radio button)
target.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
key = true;
}
});
target.addEventListener('keyup', function(e) {
if (key) {
callback(e);
}
});
window.addEventListener('keyup', function(e) {
key = false;
});
}
}
function configureDeselection(input) {
if (input.type === 'radio') {
let checked = false;
addOnBeforeClick(input, function() {
checked = input.checked;
});
input.addEventListener('click', function() {
input.checked = !checked;
});
}
}
// Usage example:
const element = document.querySelector('#my-input');
configureDeselection(element);
</script>
Source: https://dirask.com/snippets/JavaScript-deselect-input-radio-element-on-second-click-DlBRrj