我在这里遇到问题,我需要一些帮助
我的表格看起来像
要求: 如果单击按钮,如果其中之一大于100,我不想保存记录字段 我尝试了这段代码
$('.accept').click(function() {
$(this).parentsUntil('div.record').find('[name^="marks"]').each(function() {
var subjectID = $(this).attr('id');
var marks = $(this).val();
// check value
if(marks > 100) {
alert("error");
return false;
}
// save marks of this subject
// code to insert record into database table
});
return false;
});
如果用户填写为:物理= 83,数学= 89,生物学= 102,英语= 94 然后我的代码将前两个主题插入数据库,第三个主题停止并返回false
但是我希望我的程序不要在任何主题大于100的情况下插入任何标记
任何人都知道怎么了。
答案 0 :(得分:1)
问题是您正在code to insert record into database table
循环中运行each
-好吧,当然,时间沿一个方向传播,发现问题后就不能倒带,然后说:“哦,不,不要执行以前的迭代”
最简单的解决方案是验证WHOLE表单,然后将数据发送到数据库
$('.accept').click(function() {
const marks = $(this).parentsUntil('div.record').find('[name^="marks"]');
let valid = true;
marks.each(function() {
var marks = $(this).val();
if (marks > 100) {
alert("error");
valid = false;
return false; // I gather this terminates the each loop? I don't know jQuery at all
}
}
if (valid) {
marks.each(function() {
var subjectID = $(this).attr('id');
var marks = $(this).val();
// save marks of this subject
// code to insert record into database table
});
}
return false;
});