[英]checked first radio button as default using javascript only
<input id="a" type="radio" name="radioButton">
<input id="b" type="radio" name="radioButton">
<input id="c" type="radio" name="radioButton">
<input id="d" type="radio" name="radioButton">
Lets say I have four radio buttons and how do I make the first-child
to be checked
as default by using just javascript, no jQuery please. 可以说我有四个单选按钮,我如何仅使用JavaScript而不是jQuery来使第
first-child
成为默认checked
。
This is what I have done but did not work. 这是我所做的,但是没有起作用。 Thanks in advance.
提前致谢。
document.querySelectorAll('[name=radioButon]:first-child').checked = true;
The reason your example wasn't working was because .querySelectorAll()
returns a NodeList
of elements . 您的示例无法正常运行的原因是因为
.querySelectorAll()
返回了元素的NodeList
。 You would need to iterate over each element in the list in order to set the checked
property to true
: 您需要遍历列表中的每个元素,以便将
checked
属性设置为true
:
var elements = document.querySelectorAll('[name=radioButton]:first-child');
Array.prototype.forEach.call(elements, function(el) { el.checked = true; });
Alternatively, you could also access the first matching element: 另外,您也可以访问第一个匹配的元素:
document.querySelectorAll('[name=radioButton]')[0].checked = true;
// or..
document.querySelector('[name=radioButton]').checked = true;
As a side note, you also had a typo. 附带说明,您也有错字。
The attribute selector [name=radioButon]
should have been [name=radioButton]
. 属性选择器
[name=radioButon]
应该是[name=radioButton]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.