首页 > 解决方案 > 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

标签: javascriptjqueryloops

解决方案


您需要调用本机表单提交而不是 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();
    });
  }
});

推荐阅读