Search code examples
htmlformsfrontendweb-frontend

How to make specific radio button in HTML5 with automatically selecting Specify while manually adding data


I am working on a web interface for taking inputs in such a way that imagine there are three radio buttons with specific functions,and one of radio input function also has number input along with it. Take a look at example:

<h2>How many cars you own?</h2>

<form>
<input type="radio" name="car" checked>One<br>
<input type="radio" name="car">Two<br>
<input type="radio" name="car">Specify
<input type="number" name="car"><br>
</form>

Actually this works, but I want my website to be a little more smart and dynamic, so the main problem is the moment I select a number from Choose, it should automatically mark the Specify radio button, but it doesn't.And if I am choosing One or Two as my choice, it should disable the number input with a blank interface.


Solution

  • I think you want something like this

    var cars = document.getElementsByName("car");
    
    cars[3].addEventListener("input", function(e) {
    
      if (e.target.value < 1) {
        e.target.value = 1;
      }
    
      if (e.target.value === 1) {
        cars[2].checked = true;
      } else {
        cars[e.target.value - 1].checked = true;
      }
    
    });
    <h2>How many cars you own?</h2>
    
    <form>
      <input type="radio" name="car" checked>One<br>
      <input type="radio" name="car">Two<br>
      <input type="radio" name="car">Specify
      <input type="number" name="car" value="1"><br>
    </form>