使用 AJAX,我正在检查数据库中是否存在电子邮件或用户名。如果两个(或两个)之一存在,我想禁用提交按钮。
现在我设法为输入边框着色,但我坚持禁用按钮的逻辑。
我使用以下方法禁用提交按钮:
document.getElementById("submit").disabled = true;
我应该在哪里应用什么逻辑来禁用该按钮?
$(function() {
$("#username").on("change", function() {
var user = document.forms["reg_form"]["username"].value;
$.ajax({
type: 'POST',
url: 'api/checkdata.php',
data: {user: user},
dataType: 'json',
success: function(r) {
if(r=="1") {
//Exists
$("#username").css("border-color", "#ff0000");
} else {
//Doesn't exist
$("#username").css("border-color", "#2cbc21");
}
}
});
});
$("#email").on("change", function() {
var email = document.forms["reg_form"]["email"].value;
$.ajax({
type: 'POST',
url: 'api/checkdata.php',
data: {email: email},
dataType: 'json',
success: function(r) {
if(r=="1") {
//Exists
$("#email").css("border-color", "#ff0000");
} else {
//Doesn't exist
$("#email").css("border-color", "#2cbc21");
}
}
});
});
});
最佳答案
当您从服务器收到显示用户名或电子邮件存在的结果时,您将禁用提交按钮 还有:
$(function () {
$('#username').on('change', function () {
var user = document.forms['reg_form']['username'].value;
$.ajax({
type: 'POST',
url: 'api/checkdata.php',
data: {user: user},
dataType: 'json',
success: function (r) {
if (r == '1') {
// Exists
$('#username').css('border-color', '#ff0000');
$('#submit').addAttr('disabled');
isValid=false;
} else{
// Doesn't exist
$('#username').css('border-color', '#2cbc21');
$('#submit').addAttr('disabled');
isValid=true;
}
}
});
});
$('#email').on('change', function () {
var email = document.forms['reg_form']['email'].value;
$.ajax({
type: 'POST',
url: 'api/checkdata.php',
data: {email: email},
dataType: 'json',
success: function (r) {
if (r == '1') {
// Exists
$('#email').css('border-color', '#ff0000');
$('#submit').addAttr('disabled');
isValid=false;
} else {
// Doesn't exist
$('#email').css('border-color', '#2cbc21');
$('#submit').removeAttr('disabled');
isValid=true;
}
}
});
});
});
$("#submit").on('click',function(){
if (isValid){
//here you can submit form and both username and email dosenot exists
}
});
不使用 isValid 变量,如果电子邮件不存在但用户名存在,isValid 将为 false 并且不会提交表单
关于javascript - 检查用户名和电子邮件是否存在后如何禁用提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46874815/