[英]Test if a function with multiple if/else blocks return true or false in javascript
[英]javascript function with if else statements ignore return true/false
所以我有一个用isset($_POST[])
提交的 PHP 表单。 我写了一个 js 函数,它运行一些带有if-else
代码,它应该return true/false
但事实并非如此,并且无论如何都会提交表单。
我试过使用e.preventDefault()
但这对我也不起作用。 我还尝试将 true/false 放在 var 中,因为out = true/false
(当然,我将它们放在不同的 var 中,因为 if 和 else ),然后尝试将它们作为return out
。 var 中真/假的代码 -
function submitFunc(a, b) {
if (a >= b) {
alert("*Duration cannot be greater than Quoted Hours");
out = false;
}
else {
out = true;
}
window.location = "add_working_details.php";
return out;
}
原始代码 -
function submitFunc(a, b) {
if (a >= b) {
alert("*Duration cannot be greater than Quoted Hours");
// event.preventDefault();
//out = false;
return false;
window.location = "add_working_details.php";
}
else {
// out = true;
return true;
}
//return out;
// window.location = "add_working_details.php";
}
AJAX 函数——
$("#submit").click(function(){//comparing the total quoted hours with duration of time selected
ticket_id = $('#ticket_no').val();
total_hours = $('#total_hours').val();
var user_dur, ud, th;
$.ajax({
url: 'comp_time.php',
type: 'GET',
data: {ticket_id: ticket_id, total_hours: total_hours} ,
success: function (response) {
// console.log("response", response);
var resp = response;
user_dur = $('#time_duration').text();
ud = compare_time(user_dur); //user duration
th = Number(resp); //total quoted hours
submitFunc(ud, th);
}
});
});
所以我相信返回false
应该停止提交表单,然后使用window.location
它应该重定向到我想要的页面,但它没有这样做。 如果我的逻辑错误,请纠正我。 谢谢你的时间。
首先,无论事件结果如何,您的功能都应阻止提交
$("#submit").click(function(e){
e.preventDefault();
其次,您需要从函数中删除返回值,它们不会影响您的点击事件
function submitFunc(a, b) {
if (a >= b) {
alert("*Duration cannot be greater than Quoted Hours");
} else {
window.location = "add_working_details.php";
}
}
$('#form').submit(function(e) {
if (submitFunc(1, 2)) {
$.ajax({});
} else {
e.preventDefault();
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.