EN
HTML - How in simple way to make input radio element deselect on next click?
1 answers
5 points
As in the question, I am looking for a simple way to deselect <input type="radio" />
button on next click.
Is there simple solution?
1 answer
1 points
You should use JavaScript to get that effect.
e.g.:
xxxxxxxxxx
1
<label>
2
<input id="my-input" type="radio" />
3
<span>Some label ...</span>
4
</label>
5
<script>
6
7
function findTarget(input) {
8
const labels = input.labels;
9
if (labels && labels.length > 0) {
10
return labels[0];
11
}
12
return input;
13
}
14
15
function addOnBeforeClick(input, callback) {
16
const target = findTarget(input);
17
let pointer = false; // mouse and touch gestures
18
target.addEventListener('mousedown', function(e) {
19
if (e.button === 0) {
20
pointer = true;
21
}
22
});
23
target.addEventListener('mouseup', function(e) {
24
if (pointer) {
25
callback(e);
26
}
27
});
28
window.addEventListener('mouseup', function(e) {
29
pointer = false;
30
});
31
if (input.type === 'radio' || input.type === 'checkbox') {
32
let key = false; // key gestures (when input is focused space selects/deselects checkbox/radio button)
33
target.addEventListener('keydown', function(e) {
34
if (e.code === 'Space') {
35
key = true;
36
}
37
});
38
target.addEventListener('keyup', function(e) {
39
if (key) {
40
callback(e);
41
}
42
});
43
window.addEventListener('keyup', function(e) {
44
key = false;
45
});
46
}
47
}
48
49
function configureDeselection(input) {
50
if (input.type === 'radio') {
51
let checked = false;
52
addOnBeforeClick(input, function() {
53
checked = input.checked;
54
});
55
input.addEventListener('click', function() {
56
input.checked = !checked;
57
});
58
}
59
}
60
61
62
// Usage example:
63
64
const element = document.querySelector('#my-input');
65
66
configureDeselection(element);
67
68
</script>
Source: https://dirask.com/snippets/JavaScript-deselect-input-radio-element-on-second-click-DlBRrj
0 commentsShow commentsAdd comment