Languages

HTML - How in simple way to make input radio element deselect on next click?

5 points
Asked by:
Violetd
925

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
Answered by:
Violetd
925

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

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join