var validated = false;
$('input').each(function(){
if($(this).val() == ''){
alert("All fields are compulsory!");
}else{
validated = true;
}
});
if(validated == true){
window.location.href = "#next";
}
如果未填写所有字段,我在检测并阻止用户转到下一页时遇到问题。以上是我尝试的代码,但它有一个缺陷。
答案 0 :(得分:3)
您需要更改循环逻辑。
您的逻辑将validated
标志更新为true,即使1输入有值,而您需要将初始值更新为true,然后当第一项被发现为无效时,您也可以停止循环你只有一个共同的信息。
var validated = true;
$('input').each(function () {
if ($(this).val() == '') {
alert("All fields are compulsory!");
validated = false;
//stop the loop
return false;
}
});
if (validated == true) {
window.location.href = "#next";
}