工作演示 for A / B / C
案例:http: //jsfiddle.net/hfLwB/
行为:只要输入字段之一设置为 nu,她的值将允许计算发生,如果所有 3 个字段为空,则会出错。您还会注意到 class.at_least_one
和addMthod: require_from_group
。
Anyhoo 代码应该说得更好。
好的链接:http ://docs.jquery.com/Plugins/Validation
希望能帮助到你 :)
HTML
<form action="results.whatever" target="_blank" id="HULK">
<div style="clear:both">
<label for="a">A</label>
<div style="float:right">
<input name="a" type="text" class="at_least_one idleField"></div>
</div>
<div style="clear:both">
<label for="b">B</label>
<div style="float:right">
<input name="b" type="text" class="at_least_one idleField">
</div>
</div>
<div style="clear:both">
<label for="c">C</label>
<div style="float:right">
<input name="c" type="text" class="at_least_one idleField">
</div>
</div>
<div id="button">
<input name="" type="submit" value="Calculate" class="calc_button" style="cursor:hand">
</div>
</form>
<div id="errorContainer">
<h4>errors</h4>
<ol>
</ol>
</div>
代码
jQuery.validator.addMethod("require_from_group", function(value, element, options) {
var numberRequired = options[0];
var selector = options[1];
var fields = $(selector, element.form);
var filled_fields = fields.filter(function() {
// it's more clear to compare with empty string
return $(this).val() != "";
});
var empty_fields = fields.not(filled_fields);
// we will mark only first empty field as invalid
if (filled_fields.length < numberRequired && empty_fields[0] == element) {
return false;
}
return true;
// {0} below is the 0th item in the options field
}, jQuery.format("Please fill out at least {0} of these fields."));
$(document).ready(function(){
var container = $('#errorContainer');
$("#HULK").validate( {
// We must to force validation of entire form because
// when we remove value from 2-nd field
// the 1-st field becomes invalid.
onfocusout: function() { $("#HULK").valid() },
onkeyup: function() { $("#HULK").valid() },
rules: {
// note: you can use variable to avoid repeating
// of the same code
a: {
number: true,
require_from_group: [1, ".at_least_one"]
},
b: {
number: true,
require_from_group: [1,".at_least_one"]
},
c: {
number: true,
require_from_group: [1,".at_least_one"]
}
},
success: function(label) {
label.html(" ").addClass("checked");
},
errorContainer: container,
errorLabelContainer: $("ol", container),
wrapper: 'li',
meta: "validate"
});
});