Search code examples
javascripthtmlformsradio-button

How do you disable change in radio button selection using keyboard arrows?


I have an HTML form with 6 radio buttons. Each radio button, when selected, makes an API call to the backend and fetches some data to populate the next select input in the form. If one selects a radio button and then holds the up or down arrow key, then the radio button selection cycles very rapidly and we see a massive number of API calls being made to the backend. Is there a way to disable the radio selection using either the up/down arrows? or do I have to prevent it through JavaScript?


Solution

  • The keyCode property is deprecated. So the approach would be:

        var radioButtons = document.querySelectorAll('input[type="radio"]');
        
        radioButtons.forEach(function (radioButton) {
          radioButton.addEventListener('keydown', function (event) {
            if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
              event.preventDefault();
            }
          });
        });
        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Radio Button Example</title>
        </head>
        <body>
        
        <form>
        <input type="radio" name="option" id="option1" value="1"> Option 1
        <input type="radio" name="option" id="option2" value="2"> Option 2
        <input type="radio" name="option" id="option3" value="3"> Option 3
        <input type="radio" name="option" id="option4" value="4"> Option 4
        <input type="radio" name="option" id="option5" value="5"> Option 5
        <input type="radio" name="option" id="option6" value="6"> Option 6
        
        <!-- Additional form elements and API response handling -->
        </form>
        </body>
        </html>

    This script adds a keydown event listener to each radio button. When the arrow keys are pressed, it prevents the default behavior, which in this case is the cycling through options. This should help prevent the rapid API calls triggered by the arrow keys. Adjust the script as needed based on your specific HTML structure and requirements.