javascript - 如何检测是否已使用 jQuery 选择了组中的单选按钮

标签 javascript jquery html input

我已经完成了 95% 的编写 HTML5“必需”属性回退,我遇到了一个小问题,据我所知,我已经走到了尽头!

什么有效: 检测“必需”属性,循环遍历并以多种方式提醒用户(提交时将数据输入字段)。

问题: 我将表单更进一步,并且还想制作必需的复选框和单选按钮。通过这样做,我需要为每个单选/复选框添加一个必需的属性。我需要找出如何区分按钮组,因为目前您需要勾选/取消勾选两组按钮以使表单验证并让您提交。因此,简而言之,例如,我有三个必需的 radio ,每个都需要打勾,我如何在循环输入时检测到其中一个必需的 radio /选中的 radio 被打勾 - 我假设这将通过匹配 ' 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" />

查询

$(".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

关于javascript - 如何检测是否已使用 jQuery 选择了组中的单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16499285/

相关文章:

javascript - 为什么这会连接而不是相加

javascript - 多个级别的高度 100%

jquery - 生成的 div 的数字和换行?

javascript - iPad : when using swipe event the entire page is moving

javascript - 如何通过创建div来隐藏JSON数据

javascript - Node.js 事件.js :72 error

javascript - 对InfoWindow使用mouseover和mouseout会导致InfoWindow闪烁并连续触发mouseover和mouseout事件

javascript - 无法读取未定义的 Backbone.js 属性 'bind'

html - 如何在 anchor 标记中设置不同的 CSS 样式?

javascript - 如何在更改事件上显示特定输入的 native 验证错误?