简体   繁体   English

仅使用javascript将第一个单选按钮检查为默认设置

[英]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

Example Here 这里的例子

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: 另外,您也可以访问第一个匹配的元素:

Example Here 这里的例子

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.

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