jlhonora
jlhonora

Reputation: 10709

Decouple validity of two radio inputs with same name

I have a form with two <input>s with the same name. When one of them is required and unselected (thus, invalid), the other one is also characterized as invalid:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>

<body>

  <form id="form">
    <input id="rad1" type="radio" name="my radio 3" value="option 1" required>
    <input id="rad2" type="radio" name="my radio 3" value="option 2">
  </form>

  <script>
    function checkValid() {
      console.log('Should be valid form: ' + document.getElementById('form').checkValidity());
      console.log('Rad1 should show false:  ' + document.getElementById('rad1').checkValidity());
      console.log('Rad2 should show true:  ' + document.getElementById('rad2').checkValidity());
    }

    checkValid();
  </script>

</body>

</html>

I would expect the second radio input to be valid. How can I make #rad2 valid (i.e. checkValidity() return true)? Why is the validity coupled between these two radios?

I read every possible MDN doc about this but I can't find an explanation.

Upvotes: 0

Views: 37

Answers (1)

Keith
Keith

Reputation: 5381

When you set a radio button group as required, the requirement is that an option is selected. If you want to verify that a specific option is checked, you will need to use something like var selected = document.querySelectorAll('#Rad1:checked');var isSelected = selected.length > 0 ? true: false;

Notice how as you check the radios in my adjusted snip below, they both change to TRUE:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>

<body>

  <form id="form">
    <input id="rad1" type="radio" name="my radio 3" value="option 1" required>
    <input id="rad2" type="radio" name="my radio 3" value="option 2">
  </form>

  <script>
    function checkValid() {
      console.log('Should be valid form: ' + document.getElementById('form').checkValidity());
      console.log('Rad1 should show false:  ' + document.getElementById('rad1').checkValidity());
      console.log('Rad2 should show true:  ' + document.getElementById('rad2').checkValidity());
    }

    checkValid();
    $('[name="my radio 3"]').on('change', function() {
      checkValid();
    })
  </script>

</body>

</html>

Upvotes: 1

Related Questions