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

jQuery提交问卷时如何获取含未选中radio的全部答题数据

实现方案

核心调整思路

原有逻辑以单个单选按钮为遍历单位,只能收集到选中项的数据,调整为以单道题目为遍历单位,即可保证每道题无论是否作答都生成对应记录:

  • 遍历所有题目容器.question_choices_wrapper,每个容器对应一道题
  • 检测当前题目容器内是否存在选中的单选按钮
    • 存在选中项:按原有规则拼接答题数据存入数组
    • 不存在选中项:仅保存题目ID,答题相关字段设为默认标识值,标记为未作答

修正后的JS代码

const answers = [];
// 逐题遍历收集数据
$('.question_choices_wrapper').each(function () {
  const $currentQuestion = $(this);
  // 查找当前题已选中的单选按钮
  const $selectedOption = $currentQuestion.find('input[type="radio"]:checked');
  // 同题下所有单选的question_id一致,直接取第一个的属性值即可
  const questionId = $currentQuestion.find('input[type="radio"]').data('question_id');

  if ($selectedOption.length) {
    // 已答题:按原有逻辑存值
    answers.push({
      question_id: questionId,
      answer_id: $selectedOption.val() == "" || $selectedOption.val() == undefined ? 0 : $selectedOption.val(),
      answer_text: $selectedOption.parent().find('span').text() == "" ? 0 : $selectedOption.parent().find('span').text()
    });
  } else {
    // 未答题:仅存题目ID,其余字段设为默认未答标识
    answers.push({
      question_id: questionId,
      answer_id: 0,
      answer_text: 0
    });
  }
});

效果说明

  • 最终生成的answers数组长度和题目总数完全一致,不会出现漏题记录
  • 未作答的题目可以通过answer_id === 0的规则直接筛选识别,无需额外比对全量题目ID列表
  • 原有已答题的取值逻辑完全保留,不会影响已选答案的数据准确性,现有HTML结构无需任何调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 00:12:27