search

Home  >  Q&A  >  body text

How to check if radio button group is required

I have a dynamic radio button group where the required attribute may not be specified on all inputs.

<form name="myform">
    <input type="radio" id="option1" name="foo" value="First" >
    <input type="radio" id="option2" name="foo" value="Second" required>
    <input type="radio" id="option3" name="foo" value="Third">
    <input type="radio" id="option4" name="foo" value="Fourth">
</form>

Is there a way in JavaScript to check if a radio button group is required without iterating over all the inputs in the group?

I looked at the validity.missingValue property of the input element and it is valid when the radio button is not selected, but I don't have a solution for when the field is valid. Currently I have the following code, but it would be great if there were some other properties that could be used, for example on HTMLInputElement or RadioNodeList.

function isRequired() {
    return Array.from(document.myform.foo).some(i => i.required)
}

P粉716228245P粉716228245230 days ago389

reply all(1)I'll reply

  • P粉131455722

    P粉1314557222024-04-04 14:34:50

    Maybe this is the case?

    const myForm = document.forms['my-form'];
    
    console.log( !!myForm.querySelector('input[name="foo"][required]') )  // true
    <form name="my-form">
      <input type="radio" name="foo" value="First" >
      <input type="radio" name="foo" value="Second" required >
      <input type="radio" name="foo" value="Third" >
      <input type="radio" name="foo" value="Fourth" >
    </form>

    reply
    0
  • Cancelreply