我的页面上有这个脚本:
<script type='text/javascript'>
$(document).ready(function() {
$('#TotalHours').attr('name', 'TotalHours'); // jQuery validation requires field names to be set
$.validator.addMethod("hours", function(value, element) {
var totalHours = 0;
$('select').each(function(i, sel) {
var hours = $(sel).find(":selected").text();
if (hours != "")
totalHours += parseFloat(hours);
});
var reportedTotalHours = parseFloat($("#TotalHours").text());
var difference = abs(totalHours - reportedTotalHours);
return difference >= 0.25; // discrepancy must be less than a quarter hour
});
$('form').bind('submit', function() {
$("#TheForm").validate({
rules: {
TotalHours: {
hours: true
}
}
});
});
});
</script>
前几天我让它工作,但现在提交表单时,它没有经过验证(如果我在绑定到submit
的函数中设置了断点,它永远不会被命中(。。。我能打碎什么?
edit:这是提交按钮的处理程序,如果它有帮助的话:
<script type='text/javascript'>
function __E374_onclick(){
try{$("#TheForm").validate();
if(!$("#TheForm").valid()){alert('The data you have entered is not valid. Please complete all required fields and correct any data entry errors.'); return;}
var pm=$("#TheForm").serialize();$.post("/Action/Do/", pm, function(d){
switch(true){
case (null==d):dm("The server returned an unexpected response.");break;
case (!d.Valid):case (!d.Successful):dm(d.Message);break;
case (d.Successful):dm(d.Message);fu("EditAssessment");break;
default:dm("An unexpected condition occurred.");break;}});
}catch(e){}}
</script>
以及提交按钮本身:
<input type='button' id="__E374" class="button" value="Save" onclick="__E374_onclick();"/>
$('form').bind('submit', function() {
$("#TheForm").validate({
....
不能将.validate()
包装在提交处理程序中。插件已经在自动捕获提交事件,所以这毫无意义;并且它阻止插件在表单上初始化自己,直到第一次提交事件(BTW-jQuery.bind()
已被弃用(
.validate()
方法用于初始化表单上的插件,并在创建表单后调用,通常在ready
事件处理程序中调用。
<input type='button' ....
插件会忽略来自<button>
和type="button"
的点击。您需要将其更改为type="submit"
。
有关典型用法和示例,请参阅SO Wiki页面。