我有这个jQuery,用于检查文本字段(id_code
)的值是否与选择字段(id_tipAux
)中的任何可用值相似。
用户不应在文本输入(代码)中提交与选择字段(类型)中已经存在的值相似的值。
我正在使用SweetAlert。
这是我的jQuery代码:
$('#frmCreateNew').submit(function(e) {
e.preventDefault(); // I prevent the post to submit before checking it
var codeExists = false;
var types = document.getElementById('id_tipAux');
var code = document.getElementById('id_code').value;
code = code.toUpperCase(); //select vals are all uppercase
console.log('Input : ' + code +);
var i;
for (i = 0; i < types.length; i++){ // iterate all the values of the select field
console.log(types.options[i].value);
if(code == type.options[i].value){ //checks if any of them is equal to the text input value
codeExists = true; //sets the var to true in order to prevent a submit
swal("The code already exists.", "Please type another code", "error");
}
}
if(codeExists == false) { //var is false so it allows to submit
swal("New type created!", {icon: "success",})
.then((value) => {
console.log(value)
$(this).submit() // the form is submitted and the infinite loop starts here
});
}
});
使用此jQuery,如果用户发送的文本输入等于任何选择字段选项,则我尝试停止提交。它确实有效,但是问题出在用户发送可接受的值时,由于$this.submit()
触发了无限循环,因为该方法正在等待为frmCreateNew提交
答案 0 :(得分:3)
您需要调用本机表单提交而不是jQuery包装的表单提交:
$('#frmCreateNew').submit(function (e) {
e.preventDefault();
var codeExists = false;
var types = document.getElementById('id_tipAux');
var code = document.getElementById('id_code').value;
code = code.toUpperCase(); //select vals are all uppercase
console.log('Input : ' + code + );
var i;
for (i = 0; i < types.length; i++) {
console.log(types.options[i].value);
if (code == type.options[i].value) {
codeExists = true; //sets the var to true in order to prevent a submit
swal("The code already exists.", "Please type another code", "error");
}
}
if (codeExists == false) { //var is false so it allows to submit
swal("New type created!", {
icon: "success",
})
.then((value) => {
console.log(value)
//$(this).submit() // the form is submitted and the infinity loop starts here
// Do this
this.submit();
});
}
});