繁体   English   中英

如何使用JS将必需属性添加到单选按钮?

[英]How to add required attribute with JS to radio button?

我正在尝试将必需属性添加到使用javascript的单选输入中。 我目前有document.getElementsByClassName("LMB")[0].required = true; ,这给了我错误error.getElementsByClassName(...)[0]未定义。

这是我正在使用的html代码。

<input type="radio" name="LMB" id="yes" value="Yes">
<label for="yes">Yes</label>
<input type="radio" name="LMB" id="no" value="No">
<label for="no">No</label>

您的输入没有class="LMB" ,将其添加class="LMB"试:

 document.getElementsByClassName("LMB")[0].required = true; 
 <input class="LMB" type="radio" name="LMB" id="yes" value="Yes"> <label for="yes">Yes</label> <input class="LMB" type="radio" name="LMB" id="no" value="No"> <label for="yes">No</label> 

但是,如果要使用name属性,则可以使用document.getElementsByName

 document.getElementsByName("LMB")[0].required = true; 
 <input type="radio" name="LMB" id="yes" value="Yes"> <label for="yes">Yes</label> <input type="radio" name="LMB" id="no" value="No"> <label for="yes">No</label> 

您忘记了在输入标签中使用class属性

<input type="radio" name="LMB" id="yes" class="LMB" value="Yes">
<label for="yes">Yes</label>
<input type="radio" name="LMB" id="no" class="LMB" value="No">
<label for="yes">No</label>

定位input元素的name属性时使用的正确方法是

document.getElementsByName

参见https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementsByName

 document.getElementsByName("LMB")[0].required = true; 
 <input type="radio" name="LMB" id="yes" value="Yes"> <label for="yes">Yes</label> <input type="radio" name="LMB" id="no" value="No"> <label for="no">No</label> 


另外,您的第二个标签应使用for="no"

您应该像下面这样使用

 document.getElementsByName("LMB")[0].setAttribute("required","required"); 
 <input type="radio" name="LMB" id="yes" value="Yes"> <label for="yes">Yes</label> <input type="radio" name="LMB" id="no" value="No"> <label for="no">No</label> 

[...]它仅返回具有给定类名的指定根元素的后代元素。

https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementsByClassName

在您的示例中,您的输入没有任何类名:

<input class="LMB" type="radio" name="LMB" id="yes" value="Yes">
<label for="yes">Yes</label>
<input class="LMB" type="radio" name="LMB" id="no" value="No">
<label for="yes">No</label>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM