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

如何用JavaScript实时获取单选按钮(radio button)的选中值

实时获取单选框切换值的解决方案

你之前的代码仅在页面加载时执行一次,没有监听单选框的切换动作,所以无法实时捕获选中值。要实现需求,需要给单选框绑定change事件,在用户切换选项时触发逻辑。

原生JavaScript实现

// 获取所有name为promotioncases的单选框元素
const radios = document.querySelectorAll('input[name="promotioncases"]');

// 为每个单选框绑定change事件
radios.forEach(radio => {
  radio.addEventListener('change', function() {
    if (this.checked) {
      console.log('选中项ID:', this.id);
      console.log('选中项value:', this.value);
      console.log('data-target属性值:', this.dataset.target);
      console.log('data-nom属性值:', this.dataset.nom);
    }
  });
});

jQuery实现

因为你已经引入了jQuery,也可以用更简洁的写法:

// 监听单选框的change事件
$('input[name="promotioncases"]').on('change', function() {
  const selected = $(this);
  console.log('选中项ID:', selected.attr('id'));
  console.log('选中项value:', selected.val());
  console.log('data-target属性值:', selected.data('target'));
  console.log('data-nom属性值:', selected.data('nom'));
});

注:你之前代码里的attr("radio-value")无效,因为你的单选框没有该属性,需要通过value或自定义的data-*属性获取对应值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:51:09