JQuery - 检查所有单选按钮是否为“否”

时间:2014-12-19 17:03:49

标签: jquery

我有一些代码可以创建任意数量的RadioButton列表。 HTML是

<div id="ConfirmCCLChoice" class="ConfirmChoice">
  <span>
    <input class="rbl" data-val="true" data-val-required="Please Select Yes or No" id="rbl" name="Confirm[i].Taken" type="radio" value="true" />
    Accepted
  </span>
  <span>
    <input checked="checked" class="rbl" id="rbl" name="Confirm[i].Taken" type="radio" value="false" />
    Declined
  </span>
</div>

其中i是单选按钮列表的索引。

我需要的是一些javascript或jquery来检查所有单选按钮是否已设置为&#34;否&#34;。此时,我需要启用文本区域,以便客户可以解释为什么所有答案都是否定的。 (这一点很简单)。

到目前为止我所拥有的是这样,我只是试图获得每组的检查值。但是,它正在做的是为每一行运行2 *,而不是一次。 (所以我怀疑它是针对每个按钮运行的,而不是每个单选按钮组

$(document).ready(function () {
  $('#ConfirmChoice input').change(function () {           
    $(':radio').each(function() { // loop through each radio button
      var nam = $(this).attr('name'); // get the name of its set
      alert($(':radio[name="' + nam + '"]:checked').val());
    });
  });
});

那么我应该如何改变这一点,以便我遍历每个单选按钮组并提醒值,而不是每个单选按钮?

4 个答案:

答案 0 :(得分:0)

使用选中的选择器怎么样?像这样:

 var data = "_a=add" + $.map($("input:radio:checked"), function(elem, idx) {
                    return "&"+ $(elem).attr("name") + "=" + $(elem).val();
                });

应仅返回已检查的那些,如果结果为null / 0,则不检查任何内容,并且所有单选按钮=“否”

答案 1 :(得分:0)

您将遍历已检查的无线电:

 $("input:radio:checked").each(function() { // loop through each radio button
        alert($(this).val());
 });

我可能会检查至少一个“是”,例如:

var all_no = $('input:radio:checked').filter(function() { return $(this).val() == "Yes"; }).length == 0;

或者,设置textarea禁用属性:

$('textarea').prop('disabled', 
    $('input:radio:checked').filter(function() { return $(this).val() == "Yes"; }).length != 0);

答案 2 :(得分:0)

所以一定要做这样的事情。之后everythingTrue将填充您需要的值:

$(document).ready(function() {
  var everythingTrue = true;
  $(':radio').each(function() {
    var $that = $(this);
    if($that.data('val') !== true) { // Depends on what should be "no"
      everythingTrue = false;
    }
  });
});

但我认为你真正希望拥有的是以下代码行:

我在那做了什么?我刚刚将上面的代码添加到一个函数中,每次用户更改任何单选按钮时都会触发该函数。如果用no检查每个单选按钮,弹出窗口就会显示(我的命令停留在哪里)。

$(document).ready(function() {
  var everythingTrue = true
    , checkValues = function () {
        $(':radio').each(function() {
          var $that = $(this);
          if($that.data('val') !== true) { // Depends on what should be "no"
            everythingTrue = false;
          }
        });
      };

  $(':radio').on('change', function() {
    checkValues();
    if(everythingTrue == false) {
      // Now you can show your popup here why
      // User checked everything with 'no'
    } else {
      // Don't forget to hide it again if
      // something is checked with 'yes'
    }
  })
});

答案 3 :(得分:0)

您可以根据拒绝的单选按钮数量计算已检查拒绝的单选按钮的数量,并根据该数据启用/禁用textarea:

$('input').change(function () {
    $('textarea').prop('disabled', !($('.ConfirmChoice').find('input[value="false"]:checked').length == $('.ConfirmChoice').find('input[value="false"]').length))
})

<强> jsFiddle example

相关问题