How to check if radio button group is required
P粉716228245
P粉716228245 2024-04-03 16:23:29
0
1
307

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粉716228245
P粉716228245

reply all(1)
P粉131455722

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!