如何使用jQuery检测组中的单选按钮是否被选中

How to detect if a one radio button in a group has been selected with jQuery

本文关键字:单选按钮 是否 jQuery 检测 何使用      更新时间:2023-09-26

我已经完成了95%的HTML5 'required'属性回退,我遇到了一个小问题,在我的知识中我已经走到了尽头!

哪些是有效的方式:检测'required'属性,循环并以多种方式提醒用户(onsubmit和向字段中输入数据)。

问题:我采取了进一步的形式,并希望使复选框和单选按钮也是必需的。通过这样做,我需要为每个单选/复选框添加必需的属性。我需要找出如何区分这组按钮,因为目前您需要勾选/取消勾选这两组按钮的表单来验证并让您提交。因此,简而言之,我有三个必需的无线电,例如,每个都需要被打勾,我如何在循环输入时检测到其中一个所需的无线电/检查被打勾-我假设这将通过匹配'name'属性来完成,如果name组中没有被选中,则只警报一个错误。

这是我的循环的状态,你可以看到我检测输入类型,只是不确定下一步。下面还有一个jsFiddle,如果有人愿意帮忙的话。多谢。

// loop through class name required
    $('.required').each(function () {
        // this
        var self = $(this)
        // check shorthand if statement for input[type] detection
        var checked = (self.is(':checkbox') || self.is(':radio')) ? self.is(':not(:checked)') : false
        // run the empty/not:checked test
        if (self.val() === '' || checked) {
            // show error if the values are empty still (or re-emptied)
            // this will fire after it's already been checked once
            self.siblings('.form-error').show()
            // stop form submitting
            e.preventDefault()
            // if it's passed the check
        } else {
            // hide the error
            self.siblings('.form-error').hide()
        }
    })

这是我的jsFiddle: http://jsfiddle.net/zykF9/

使用类选择器您可以存档它http://jsbin.com/owokuw/1/edit

UPDATE

为了更容易理解,这里有一个更新:

  <input type="radio" name="myradio"  class="myradio" />
<input type="radio" name="myradio"  class="myradio" />
<input type="radio" name="myradio"  class="myradio" />
<input type="radio" name="myradio"  class="myradio" />
  <input type="hidden"   id="selectedRadioYes" />
  <input type="button" id="botton" value="Botton" />
Jquery

$(".myradio").click(function(){
$("#selectedRadioYes").val(1);
});


$("#botton").click(function(){
  if($("#selectedRadioYes").val() === "1")
  alert("you can go on"); 
  else
   alert("need select one radio");
});
http://jsbin.com/owokuw/2/edit