You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript在当前网页中打印单选框选中值?

获取单选框选中值并在页面打印

首先要注意,你的原始HTML中单选框缺少value属性,这会导致无法正确获取选中的颜色值,先完善HTML代码:

<form>
  What color do you prefer?
  <input type="radio" name="colors" id="red" value="red">Red
  <input type="radio" name="colors" id="blue" value="blue">Blue
</form>
<!-- 用来打印结果的容器 -->
<div id="result"></div>

接下来提供两种常用的JavaScript实现方式:

方式一:实时监听单选框选中变化

当用户切换单选框时,自动打印选中值:

// 获取所有name为colors的单选框
const colorRadios = document.querySelectorAll('input[name="colors"]');
// 获取结果容器
const resultDiv = document.getElementById('result');

// 给每个单选框添加change事件监听
colorRadios.forEach(radio => {
  radio.addEventListener('change', function() {
    if (this.checked) {
      // 将选中值打印到页面容器中
      resultDiv.textContent = `选中的颜色是:${this.value}`;
    }
  });
});

方式二:通过按钮触发获取

添加一个按钮,点击后获取当前选中的单选框值并打印:

<!-- 新增按钮 -->
<button id="getSelectedColor">获取选中颜色</button>
const getBtn = document.getElementById('getSelectedColor');
const resultDiv = document.getElementById('result');

getBtn.addEventListener('click', function() {
  // 获取选中的单选框元素
  const selectedRadio = document.querySelector('input[name="colors"]:checked');
  if (selectedRadio) {
    resultDiv.textContent = `选中的颜色是:${selectedRadio.value}`;
  } else {
    resultDiv.textContent = '请选择一个颜色';
  }
});

补充说明

  • 如果不想额外添加容器,也可以用console.log()在浏览器控制台打印,但题目要求在同一网页中显示,所以用页面元素展示更符合需求。
  • 必须给单选框设置value属性,否则selectedRadio.value会返回空字符串(默认值),无法区分选中的是哪个选项。

内容的提问来源于stack exchange,提问作者Ratna Raju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:54:43