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

如何用jQuery校验循环生成的单选框并获取选中值?

解决方案:Radio组批量验证与选中值获取

先修正HTML的小问题

你的原始代码中<label>未绑定for属性,导致点击标签无法选中对应单选框,需要补充for属性与radio的id关联,修正后的HTML如下:

<form action="" type="POST" onsubmit="return false;">
  <div id="form_step_1">
    <div class="container">
      <div class="row">
        <div class="talepler mb-3">
          <H4>GB</H4>
          <div class="row mb-3" style="display: inline-block">
            <div class="col-sm-3 col-md-4 col-lg-3 titles">
              <input class="inputs" type="radio" id="1" name="1">
              <label class="btn btn-pill" style="display: inline-block;" for="1">16 GB</label>
              <input class="inputs" type="radio" id="2" name="1">
              <label class="btn btn-pill" style="display: inline-block;" for="2">32 GB</label>
            </div>
          </div>
          <H4>DİSPLAY</H4>
          <div class="row mb-3" style="display: inline-block">
            <div class="col-sm-3 col-md-4 col-lg-3 titles">
              <input class="inputs" type="radio" id="3" name="2">
              <label class="btn btn-pill" style="display: inline-block;" for="3">durable</label>
              <input class="inputs" type="radio" id="4" name="2">
              <label class="btn btn-pill" style="display: inline-block;" for="4">broken</label>
            </div>
          </div>
        </div>
        <button type="submit" class="btn btn-success" id="gonder">Gönder</button>
      </div>
    </div>
  </div>
</form>

jQuery实现逻辑

绑定提交按钮的点击事件,批量处理所有radio分组的验证与值收集:

$(document).ready(function() {
  $('#gonder').click(function() {
    let isValid = true;
    const selectedData = {};

    // 获取所有不重复的radio分组name
    const groupNames = $('.inputs')
      .map(function() { return $(this).attr('name'); })
      .get()
      .filter((name, index, self) => self.indexOf(name) === index);

    // 遍历每个分组验证并收集数据
    groupNames.forEach(function(name) {
      const radioGroup = $(`input[name="${name}"]`);
      const checkedRadio = radioGroup.filter(':checked');
      // 获取分组标题(如GB、DİSPLAY)
      const groupTitle = radioGroup.closest('.row.mb-3').prev('H4').text();

      // 验证是否选中
      if (!checkedRadio.length) {
        alert(`请选择${groupTitle}选项`);
        isValid = false;
        return false; // 可选:遇到第一个未选分组就停止提示,去掉则会提示所有未选分组
      }

      // 收集选中项的数据库ID和文本
      selectedData[name] = {
        dbId: checkedRadio.attr('id'),
        optionText: checkedRadio.next('label').text().trim()
      };
    });

    // 验证通过后的处理
    if (isValid) {
      console.log('所有选中数据:', selectedData);
      // 这里可以添加表单提交或其他业务逻辑
      alert('验证通过,已获取所有选中值');
    }
  });
});

核心逻辑说明

  1. 分组去重:通过map和filter获取所有唯一的radio分组name,确保每个分组只处理一次
  2. 分组验证:遍历每个分组,检查是否有选中项,未选中则弹出对应分组的提示
  3. 数据收集:验证通过后,收集每个选中项的数据库ID(radio的id)和选项文本,存储在对象中便于后续使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:36:43