检索反馈表单的单选按钮值时出现问题

Problems with retrieving radio button value for feedback form

本文关键字:问题 单选按钮 表单 检索      更新时间:2023-09-26

我正在尝试构建一个简单的反馈表单。用户将回答一系列是或否的问题。如果他们选择"否",则会向他们提供一个包含文本的评论表单。

目前,我在检索单选按钮值时遇到问题。我正试图在控制台中打印它们,但当我选择合适的选项时,什么也没发生。如果用户选择"否",则需要能够记住将要提交的评论。

我的JSFiddle在这里:http://jsfiddle.net/787x18vx/

HTML

<p>You are providing feedback</p>
<form>
  <div id="question-1">
    <label for="question-1">Is this correct?</label>
    <input type="radio" value="yes" name="choice-1" />Yes
    <input type="radio" value="no" name="choice-1" />No
  </div>
  <div id="question-2">
    <label for="question-2">Another question</label>
    <input type="radio" value="yes" name="choice-2" />Yes
    <input type="radio" value="no" name="choice-2" />No
  </div>
  <div id="question-3">
    <label for="question-3">One more question</label>
    <input type="radio" value="yes" name="choice-3" />Yes
    <input type="radio" value="no" name="choice-3" />No
  </div>
  <br />
  <button>Send Feedback</button>
</form>

jQuery

var firstInput = 'input[name=choice]';
var firstInputValue = $('input[name=choice-1]:checked').val();
$(firstInput).on('click', function() {
  console.log(firstInputValue);
  console.log($('input[name="choice-1"]:checked').val());
  console.log($('input[name="choice-2"]:checked').val());
  // if value === 'no' show comment form
});

您使用的是不存在的input[name=choice]选择器。

请改用input[type=radio]

var firstInput = 'input[type=radio]';
var firstInputValue = $('input[name=choice-1]:checked').val();
$(firstInput).on('click', function() {
  console.log(firstInputValue);
  console.log($('input[name="choice-1"]:checked').val());
  console.log($('input[name="choice-2"]:checked').val());
  // if value === 'no' show comment form
});

Fiddle

var firstInput = 'input[name=choice]';这是在寻找名称为choice的特定内容,它似乎不在您的html中。

对此有两种快速方法。首先,只需更改您的选择器:

$('input[type=radio]').on('click', function(){...

这将在点击任何无线电时触发该功能

另一种方法是使用通配符选择器:

var firstInput = 'input[name^=choice]';

^应该这样做,所以任何名称以choice开头的输入都会被选中。

这种方法应该有效,但以input[type=radio]为目标可能是更好的解决方案,

您的名字中缺少-1

var firstInput = 'input[name=choice-1]';

您的选择器正试图获取名称恰好等于"choice"的标记。您可以使用以下按前缀进行搜索

var firstInput = 'input[name|="choice"]';

这将获得名称以"choice"开头的所有标签