【问题标题】:How to detect if a one radio button in a group has been selected with jQuery如何检测是否已使用 jQuery 选择了组中的一个单选按钮
【发布时间】:2013-05-06 03:26:01
【问题描述】:

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

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

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

【问题讨论】:

  • 我是这样做的 jsfiddle.net/mplungjan/VRC6L - 但是你们使用 is(":checked").val() 来测试收音机的值,你应该什么也得不到
  • 格式正确的问题,+1

标签: javascript jquery html input


【解决方案1】:

使用类选择器,您可以将其归档 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2012-05-03
    • 2021-10-21
    • 2022-01-15
    相关资源
    最近更新 更多