[Edit]
+
0
-
0

JavaScript - deselect input radio element on second click

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
<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) { // mouse primary button test (works also when user touches screen) 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>
Reset