← 中文资源

简体中文版本

RadioNodeList 读取单选组的选中值

通过 form.elements.namedItem 拿到具名单选组:RadioNodeList.value 直接返回选中项的值,赋值即选中对应 radio;赋 '' 并不是重置—— setter 只会勾选值匹配的项,清空选中要逐个 r.checked = false;集合可迭代遍历每个输入框,初始读取永不抛错。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:form、group。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 直接运行文件,输出会带上标签,比如 initial:、after set:、same group:——输出的每一行都能指回产生它的那次调用。

常见问题

「RadioNodeList 读取单选组的选中值」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

核心语句

const form = document.querySelector('#shipping');
const group = form.elements.namedItem('speed');
group.value = 'express';

代码示例

const form = document.querySelector('#shipping');
const group = form.elements.namedItem('speed');

// RadioNodeList.value returns the checked radio's value,
// or '' when nothing is checked yet.
console.log('initial:', JSON.stringify(group.value));

// Setting value through the list checks the matching radio for you.
group.value = 'express';
console.log('after set:', group.value);

// The list is iterable: every input in the group, in DOM order.
for (const radio of group) {
  console.log(radio.value, radio.checked);
}

// The HTMLFormControlsCollection also indexes by name directly.
console.log('same group:', form.elements['speed'] === group);

// Assigning '' is NOT a reset: the value setter only ever checks a radio
// whose value matches, so an empty assignment leaves the choice untouched
// (verified in Chromium: the read-back is still 'express').
group.value = '';
console.log('still selected after assigning "":', JSON.stringify(group.value));

// Reading an untouched group never throws — '' is the 'nothing checked' signal.
// Clearing requires unchecking each input directly:
for (const radio of group) {
  radio.checked = false;
}
console.log('cleared:', JSON.stringify(group.value));