我已经完成了 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");
});
关于javascript - 如何检测是否已使用 jQuery 选择了组中的单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16499285/