javascript - jQuery 提交不停 - 无限循环
问题描述
我有这个 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
解决方案
您需要调用本机表单提交而不是 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();
});
}
});
推荐阅读
- python - 如何使用python将两个数据csv合并到一个文件中
- python - 拼接具有元数据完整性的热图像
- sql - 如何从另一个表中获取具有关联最旧值的项目列表
- azure - 使用 cli 检索 Azure 使用成本
- apache-spark - Spark SQL - 类似忽略大小写
- c++ - 如何使用 C+ 中的指针访问数组中的特定索引?
- python - 如何从 Python 中的 JSON 文件生成索引列表?
- bootstrap-4 - 带有图标的 Bootstrap 4 实现按钮的 Fontawesome?
- vcpkg - 如何为正在构建的每个端口添加编译器选项?
- python - 尝试将 s3 响应正文读取为嵌套列表,将字符作为嵌套列表中的单个元素