我在javascript中有两个函数,但只返回错误中的一个而不是两个函数。
如果我删除一个功能,那么其他功能,但如果我有2个功能,它只显示一个。
这是我的javascript:
function validateForm(event) {
event = event || window.event || event.srcElement;
var initialMonoReading = $('#InitialMonoReading').val();
var newMonoReading = $('#newMonoReading').val()
if (~~newMonoReading < ~~initialMonoReading) {
$('#MonoErrorMessage').text("New Mono Readings must be MORE than existing");
$('#MonoErrorMessage').show();
event.preventDefault();
}
else {
$('#MonoErrorMessage').hide();
}
}
function validateForm(event) {
event = event || window.event || event.srcElement;
var InitialColourReading = $('#InitialColourReading').val();
var newColourReading = $('#newColourReading').val()
if (~~newColourReading < ~~InitialColourReading) {
$('#ColourErrorMessage').text("New Colour Readings must be MORE than existing");
$('#ColourErrorMessage').show();
event.preventDefault();
}
else {
$('#ColourErrorMessage').hide();
}
}
这是我的提交:
@using (Html.BeginForm("Save", "ReadingsEntry", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "validateForm(event)"}))
这仅适用于ColourErrorMessage。但是忽略了MonoErrorMessage。何时它应该显示两个错误......
那为什么要跳过其中一个功能
答案 0 :(得分:1)
在同一范围内声明两个具有相同名称的函数将导致最新的函数覆盖前一个函数。
最好这样做:
function validateForm(event){
validateMono(event)
validateColor(event) //Or something to combine the results.
}
function validateMono(event) {
event = event || window.event || event.srcElement;
var initialMonoReading = $('#InitialMonoReading').val();
var newMonoReading = $('#newMonoReading').val()
if (~~newMonoReading < ~~initialMonoReading) {
$('#MonoErrorMessage').text("New Mono Readings must be MORE than existing");
$('#MonoErrorMessage').show();
event.preventDefault();
}
else {
$('#MonoErrorMessage').hide();
}
}
function validateColor(event) {
event = event || window.event || event.srcElement;
var InitialColourReading = $('#InitialColourReading').val();
var newColourReading = $('#newColourReading').val()
if (~~newColourReading < ~~InitialColourReading) {
$('#ColourErrorMessage').text("New Colour Readings must be MORE than existing");
$('#ColourErrorMessage').show();
event.preventDefault();
}
else {
$('#ColourErrorMessage').hide();
}
}
然后是HTML:
@using (Html.BeginForm("Save", "ReadingsEntry", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "validateForm(event)"}))