Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/90.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅使用javascript默认选中第一个单选按钮_Javascript_Html_Css_Input_Radio Button - Fatal编程技术网

仅使用javascript默认选中第一个单选按钮

仅使用javascript默认选中第一个单选按钮,javascript,html,css,input,radio-button,Javascript,Html,Css,Input,Radio Button,您的示例不起作用的原因是因为返回了。您需要迭代列表中的每个元素,以便将checked属性设置为true: 或者,您也可以访问第一个匹配元素: 作为旁注,你也有一个打字错误 属性选择器[name=radioButon]应该是[name=radioButton] <input id="a" type="radio" name="radioButton"> <input id="b" type="radio" name="radioButton"> <input

您的示例不起作用的原因是因为返回了。您需要迭代列表中的每个元素,以便将
checked
属性设置为
true


或者,您也可以访问第一个匹配元素:


作为旁注,你也有一个打字错误

属性选择器
[name=radioButon]
应该是
[name=radioButton]

<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">
document.querySelectorAll('[name=radioButon]:first-child').checked = true; 
var elements = document.querySelectorAll('[name=radioButton]:first-child');
Array.prototype.forEach.call(elements, function(el) { el.checked = true; });
document.querySelectorAll('[name=radioButton]')[0].checked = true;
// or..
document.querySelector('[name=radioButton]').checked = true;