将jQuery验证规则添加到单选按钮组 [英] Add jQuery Validation Rule to a Radio Button Group
问题描述
我正在使用 jQuery验证插件,并且我希望能够动态添加和从3个单选按钮组中删除验证.
我可以使用以下示例代码从文本字段输入中动态添加和删除验证:
<script type="text/javascript">
$(document).ready(function(){
//Add Requird Validation
$("#inputTextField").rules("add", "required");
//Remove Required Validation
$("#inputTextField").rules("remove", "required");
});
</script>
是否可以使用单选按钮执行同样的操作?
您所发布的代码可以正常工作.但是, rules('add')
必须在之后出现 .validate()
和每个input
必须包含name
属性,即使您未按name
定位.
HTML :
<form id="myform">
<input type="text" name="field" id="inputTextField" /> <br/>
</form>
jQuery :
$(document).ready(function() {
$('#myform').validate({
// other options & rules
});
// must come afer validate()
$("#inputTextField").rules("add", {
required: true
});
});
演示: http://jsfiddle.net/fnKWD/ >
是否可以使用单选按钮执行同样的操作?
当然,只需按名称或其他任何有效的jQuery选择器定位它们.
$('input[name="myname"]')
HTML :
<input type="radio" name="myname" value="0" />
<input type="radio" name="myname" value="2" />
<input type="radio" name="myname" value="5" />
演示: http://jsfiddle.net/LkJZw/ >
I'm using jQuery Validation Plugin and I want to be able to dynamically add and remove validation from 3 radio button groups.
I am able to dynamically add and remove validation from text field input using the sample code below:
<script type="text/javascript">
$(document).ready(function(){
//Add Requird Validation
$("#inputTextField").rules("add", "required");
//Remove Required Validation
$("#inputTextField").rules("remove", "required");
});
</script>
Is it possible to do the same with radio buttons?
The code as you've posted it will work fine. However, rules('add')
must come after .validate()
and each input
must contain a name
attribute even if you're not targeting by name
.
HTML:
<form id="myform">
<input type="text" name="field" id="inputTextField" /> <br/>
</form>
jQuery:
$(document).ready(function() {
$('#myform').validate({
// other options & rules
});
// must come afer validate()
$("#inputTextField").rules("add", {
required: true
});
});
Demo: http://jsfiddle.net/fnKWD/
Is it possible to do the same with radio buttons?
Of course, just target them by name or by any other valid jQuery selector.
$('input[name="myname"]')
HTML:
<input type="radio" name="myname" value="0" />
<input type="radio" name="myname" value="2" />
<input type="radio" name="myname" value="5" />
Demo: http://jsfiddle.net/LkJZw/
这篇关于将jQuery验证规则添加到单选按钮组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!