gpt4 book ai didi

javascript - 返回 false 不阻止表单提交

转载 作者:行者123 更新时间:2023-11-30 16:46:35 25 4
gpt4 key购买 nike

我正在尝试使用 $.get 请求验证一个字段。我可以看到错误消息(“计划已存在”)但正在提交表单。我想阻止提交表单。这是我的代码:

$("#add_plan_subscriptions").submit(function(event) {
var flag = true;
var subdomain_val = $('[name="plan[subdomain_type_id]"]').val();
var plan_val = $('[name="plan[plan_type_id]"]').val();
var plan_name = $('[name="plan[plan_name]"]').val();
var subdomain_type_id = subdomain_val;
var plan_name = $('[name="plan[plan_name]"]').val();
$.get("/plans/check_duplicate_plan",{subdomain_type_id: subdomain_type_id, plan_name: plan_name}, function (response) {
if (response){
event.preventDefault() ;
var element = $('[name="plan[plan_name]"]');
var message = "Plan already present";
addError(element,message)
return false;
}
else{
var element = $('[name="plan[plan_name]"]');
removeError(element)
}
})
if(subdomain_val == ""){
var element = $('[name="plan[subdomain_type_id]"]')
var message = "Please select user type"
addError(element,message)
flag = false;
}
if(subdomain_val != ""){
var element = $('[name="plan[subdomain_type_id]"]')
removeError(element)
}
if(plan_val == ""){
var element = $('[name="plan[plan_type_id]"]')
var message = "Please select plan type"
addError(element,message)
flag = false;
}
if(plan_val != ""){
var element = $('[name="plan[plan_type_id]"]')
removeError(element)
}
if (!flag){
event.preventDefault();
return false;
}
return true;
});

最佳答案

现在 $.getGET 响应之前以 async 模式调用您的表单提交函数正在调用。所以在 sync 模式下使用 ajax 而不是 $.get

            $.ajax({
url: '/plans/check_duplicate_plan',
data: { subdomain_type_id: subdomain_type_id, plan_name: plan_name},
dataType: 'json',
async:false,
type: 'GET',
success: function (response) {
if (response){
event.preventDefault() ;
var element = $('[name="plan[plan_name]"]');
var message = "Plan already present";
addError(element,message)
return false;
}
else{
var element = $('[name="plan[plan_name]"]');
removeError(element)
}
}
})

关于javascript - 返回 false 不阻止表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31158911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com