【发布时间】:2014-01-04 08:28:33
【问题描述】:
我有三个要填写数字的文本字段。这三个文本字段的总和应始终为 100。我使用 jQuery Validation 插件来简化事情,并使用.addmethod() 来验证这个案例。
我试过的:http://jsfiddle.net/NcW9V/
-- 下面发布的代码是 jsfiddle 中的内容的副本-- 我的 jQuery 代码:
//show the percentage
$("#airPercent, #seaPercent, #landPercent").change(function(){
var sPerct = $('#seaPercent').val();
var lPerct = $('#landPercent').val();
var perct = $('#airPercent').val();
var newTotal = parseInt(perct) + parseInt(lPerct) + parseInt(sPerct);
$("#totalP").empty();
$("#totalP").text(newTotal);
});
//the validator
jQuery.validator.addMethod("checkModePerct", function(value) {
total = parseInt($('#airPercent').val()) + parseInt($('#seaPercent').val()) + parseInt($('#landPercent').val());
return total == 100;
}, "Please only enter a sum total of 100%");
$("#contact-form").validate(
{
});
HTML 标记:
<form action="lane" method="post" id="contact-form" class="form-horizontal">
<legend>Mode of Transportation:</legend>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Air</th>
<th>Sea</th>
<th>Land</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>Percentage</td>
<td class="span3">
<input type="text" class="span1" name="airPercent" id="airPercent" value="0" class="required checkModePerct"/>%
</td>
<td class="span3">
<input type="text" class="span1" name="seaPercent" id="seaPercent" value="0" class="required checkModePerct"/>%
</td>
<td class="span3">
<input type="text" class="span1" name="landPercent" id="landPercent" value="0" class="required checkModePerct"/>%
</td>
<td class="span3">
<div id="totalP">
0
</div>%
</td>
</tr>
</tbody>
</table>
<input type="submit" value="submit"/>
</form>
我已经查看了许多其他示例,但我能找到的最接近的示例是 http://jsfiddle.net/wtmv3/。我玩过代码,但无法让它工作,因为我不确定jQuery.validator.classRuleSettings.checkTotal 做了什么。似乎也没有任何关于它的信息。
【问题讨论】:
标签: jquery forms jquery-validate