简体   繁体   English

jQuery的单选按钮没有检查问题

[英]JQuery No radio button checked issue

I have a series of randomly generated textbox and radio-button inputs. 我有一系列随机生成的文本框和单选按钮输入。 It's kinda like a Quiz, so what I would like to do is collect all of the inputs and send them to the server so it can evaluate them. 这有点像测验,所以我想做的是收集所有输入并将其发送到服务器,以便它可以评估它们。

Now, to make it easier, I put all of the radio-button inputs to the end. 现在,为了简化起见,我将所有单选按钮输入置于末尾。

I use the following code to collect the inputs of the textbox-types: 我使用以下代码来收集文本框类型的输入:

$('#button_submit').click(function() {
  var answer_list = '';
  $('input:text').each(function(index,data) {
    answer_list = answer_list + '$' + $(data).val();
  }
  ...
}

This works perfectly, but after this, I don't know what to do. 这可以正常工作,但是在此之后,我不知道该怎么办。 I could loop through the input:radio:checked elements and add the value of those to my string, which would work perfectly, except if the user decides to submit their answers while leaving one of the radio-button inputs empty. 我可以遍历input:radio:checked元素,并将这些元素的值添加到我的字符串中,这将很好地工作,除非用户决定在单选按钮输入之一为空的情况下提交答案。 In that case, nothing gets added to the string and the server will be missing the answer to that question and it messes everything up. 在这种情况下,字符串中将不会添加任何内容,服务器将丢失该问题的答案,并弄乱了所有内容。

So I need to add something to my string when the code realizes that there is a radio-button question, but no answer was chosen, but I have no idea how to do it. 因此,当代码意识到存在单选按钮问题,但没有选择答案时,我需要在字符串中添加一些内容,但是我不知道该怎么做。

Edit: 编辑:

HTML example: HTML示例:

<div class="form-group" id="form-group-34">
  <label class="control-label " for="question">What is 92848 &#x00D7; 71549?</label>
  <input autofocus="true" class="form-control" id="input34" name="answer" size="20" type="text" value="">
</div>
<div class="form-group" id="form-group-35">
  <label class="control-label " for="question">Is 194 divisible by 3?</label>
  <br><input id="14-answer-0" name="14-answer" type="radio" value="1">
    <label for="14-answer-0">Yes</label>
  <br><input id="14-answer-1" name="14-answer" type="radio" value="0">
    <label for="14-answer-1">No</label>
</div>
<div class="form-group" id="form-group-36">
  <label class="control-label " for="question">Determine the day of the week for 1954 Jun 26!</label>
  <br><input id="35-answer-0" name="35-answer" type="radio" value="1">
    <label for="35-answer-0">Monday</label>
  <br><input id="35-answer-1" name="35-answer" type="radio" value="2">
    <label for="35-answer-1">Tuesday</label>
  <br><input id="35-answer-2" name="35-answer" type="radio" value="3">
    <label for="35-answer-2">Wednesday</label>
  <br><input id="35-answer-3" name="35-answer" type="radio" value="4">
    <label for="35-answer-3">Thursday</label>
  <br><input id="35-answer-4" name="35-answer" type="radio" value="5">
    <label for="35-answer-4">Friday</label>
  <br><input id="35-answer-5" name="35-answer" type="radio" value="6">
    <label for="35-answer-5">Saturday</label>
  <br><input id="35-answer-6" name="35-answer" type="radio" value="0">
    <label for="35-answer-6">Sunday</label>
</div>

But the problem is, that these questions are randomly generated. 但是问题是,这些问题是随机产生的。 So there can be 5 simple textbox-type inputs, then 5 radio-button type ones, or there might be only 1 radio-button type question, and all of their attributes are generated dynamically, so I can't really put the radio-button group's name in the code, because I don't know it. 因此可能有5个简单的文本框类型的输入,然后是5个单选按钮类型的输入,或者可能只有1个单选按钮类型的问题,并且它们的所有属性都是动态生成的,所以我不能真正将单选按钮类型代码中按钮组的名称,因为我不知道。

You could use this to see if they are all checked: 您可以使用它来查看是否已全部选中:

var allRadios = $('input[name="namevalue"][type=radio]').length; 

var allCheckedRadios $('input[name="namevalue"][type=radio]').filter(function()   {
    return this.checked;
}).length;

if( allRadios == allCheckedRadios){
// do what you need
} 

whatever your name is change "namevalue" to that. 无论您的名字是什么,都将“ namevalue”更改为该名称。 The same basic logic to get the values can be applied. 可以应用获取值的相同基本逻辑。

Note: performance gain for modern browsers on these selector forms above over $('input:radio') can be had. 注意:在$('input:radio')以上的这些选择器形式下,现代浏览器的性能可获得提高。

EDIT From updated question: 编辑从更新的问题:

Here I applied the techniques above to walk through each of the form groups looking for radio buttons, and if they exist throw an alert if none are checked within that group. 在这里,我应用了上述技术来遍历每个表单组以查找单选按钮,如果它们存在,则如果在该组中未选中任何按钮,则会发出警报。 You could also create and return a Boolean value if ANY of the groups have radio selections with none selected. 如果任何一个组的无线电选择都未被选中,则您还可以创建并返回一个布尔值。 "hasUncheckedRadios" will be either 0 if none are checked or 1 if one is checked - since radio buttons within a group only select one. 如果未选中,则“ hasUncheckedRadios”将为0或如果选中一个则为1-因为组中的单选按钮只能选择一个。 You could use this logic in your validation to ensure that all of the groups have a valid checked radio button (IF they contain a radio that is); 您可以在验证中使用此逻辑,以确保所有组都有一个有效的选中单选按钮(如果它们包含一个单选按钮);

function checkRadios() {
  var allGroups = $('.form-group');
  allGroups.each(function() {
    var allRadios = $(this).find('input[type=radio]').length;
    var hasUncheckedRadios = $(this).find('input[type=radio]').filter(function() {
      return this.checked;
    }).length;
    console.log('total:' + allRadios + ' checked:' + hasUncheckedRadios);
    // if allRadios is > 0 then radios exist and hasUncheckedRadios == 0 none are checked
    if (allRadios && !hasUncheckedRadios) {
      alert("Form Group" + $(this).attr('id') + " has radio buttons unaswered");
    }
  });
}
$('#checkem').on('click', function() {
  console.log('checking...');
  checkRadios();
});

fiddle with it here: https://jsfiddle.net/MarkSchultheiss/nv7cjpr2/ 在这里摆弄它: https : //jsfiddle.net/MarkSchultheiss/nv7cjpr2/

I would iterate a bit more: https://jsfiddle.net/Twisty/ghc7u2ab/ 我会进一步迭代: https : //jsfiddle.net/Twisty/ghc7u2ab/

HTML 的HTML

<div class="form-group" id="form-group-34">
  <label class="control-label " for="question">What is 92848 &#x00D7; 71549?</label>
  <input autofocus="true" class="form-control" id="input34" name="answer" size="20" type="text" value="">
</div>
<div class="form-group" id="form-group-35">
  <label class="control-label " for="question">Is 194 divisible by 3?</label>
  <br>
  <input id="14-answer-0" name="14-answer" type="radio" value="1">
  <label for="14-answer-0">Yes</label>
  <br>
  <input id="14-answer-1" name="14-answer" type="radio" value="0">
  <label for="14-answer-1">No</label>
</div>
<div class="form-group" id="form-group-36">
  <label class="control-label " for="question">Determine the day of the week for 1954 Jun 26!</label>
  <br>
  <input id="35-answer-0" name="35-answer" type="radio" value="1">
  <label for="35-answer-0">Monday</label>
  <br>
  <input id="35-answer-1" name="35-answer" type="radio" value="2">
  <label for="35-answer-1">Tuesday</label>
  <br>
  <input id="35-answer-2" name="35-answer" type="radio" value="3">
  <label for="35-answer-2">Wednesday</label>
  <br>
  <input id="35-answer-3" name="35-answer" type="radio" value="4">
  <label for="35-answer-3">Thursday</label>
  <br>
  <input id="35-answer-4" name="35-answer" type="radio" value="5">
  <label for="35-answer-4">Friday</label>
  <br>
  <input id="35-answer-5" name="35-answer" type="radio" value="6">
  <label for="35-answer-5">Saturday</label>
  <br>
  <input id="35-answer-6" name="35-answer" type="radio" value="0">
  <label for="35-answer-6">Sunday</label>
</div>
<button id="button_submit">Submit</button>

JQuery jQuery查询

$("#button_submit").click(function() {
  var answer_list = {};
  $(".form-group").each(function(i, v) {
    console.log("Index:", i, "ID: [", $(v).attr("id"), "]");
    answer_list[$(v).attr("id")] = {};
    var ind = $(v).find("input");
    $.each(ind, function(i2, el) {
      console.log("Type of Element:", $(el).attr("type"));
      switch ($(el).attr("type")) {
        case "text":
          answer_list[$(v).attr("id")][$(el).attr("id")] = ($(el).val() != "") ? $(el).val() : null;
          break;
        case "radio":
          var isAnswered = false;
          $(el).each(function(i3, rad) {
            if ($(rad).is(":checked")) {
              answer_list[$(v).attr("id")][$(rad).attr("name")] = $(rad).val();
              isAnswered = true;
            }
            if (!isAnswered) {
              answer_list[$(v).attr("id")][$(el).eq(0).attr("name")] = null;
            }
          });
          break;
      }
    });
  });
  console.log(answer_list);
  return false;
});

Possible Result 可能的结果

answer_list: {
  form-group-34: {
    input34: null
  },
  form-group-35: {
    14-answer: 0
  },
  form-group-36: {
    35-answer: null
  }
}

This will iterate each group and look for an answer. 这将迭代每个组并寻找答案。 If one is found, the value is added. 如果找到一个,则将值相加。 If not, null is added as the result. 如果不是,则将null添加为结果。

loop class group that has radio then use .prop("checked") 具有广播的循环类组,然后使用.prop("checked")

  var frmGroup= 0, checked= 0;
  $('.form-group').each(function(index) {
    if ($(this).children('input:radio').length > 0) {
      frmGroup++;
      $(this).children('input:radio').each(function(index) {
        if ($(this).prop("checked") == true) {
          checked++;
        }
      });
    }
  });

  if(frmGroup != checked)...

working example: https://jsfiddle.net/nsL3drz5/ 工作示例: https : //jsfiddle.net/nsL3drz5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM