Search code examples
javascripthtmldomradiobuttonlist

After selecting one radio button, I want the remaining buttons to become disabled


I am working on a pong game in java script where one can change the difficulty level using a set of radio buttons

<form action="">
        <input type="radio" name="level" value="8">Beginner<br> 
        <input type="radio" name="level" value="4">Intermediate<br>
        <input type="radio" name="level" value="2">Pro<br>        
      </form>

The level adjusts well on the first try but when someone clicks on another radio button the game court is affected and keeps on refreshing. I am using html 5 and set the fps to 60. What I wanted is after a new page refresh, when one selects one radio button, the remaining buttons should become disabled till the user refreshes the page. Is there a way to do this in vanilla js?


Solution

  • You can loop over radio buttons collection and change their disabled status on change event. For example like this:

    var radios = [].slice.call(document.querySelectorAll('input[name=level]'));
    
    radios.forEach(function(radio) {
        radio.addEventListener('change', function() { 
            radios.forEach(function(r) {
                r.disabled = r !== radio;
            });
        });
    });
    <form action="">
      <input type="radio" name="level" value="8">Beginner<br>
      <input type="radio" name="level" value="4">Intermediate<br>
      <input type="radio" name="level" value="2">Pro<br>
    </form>