j查询提交不间断 - 无限循环



我有这个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();
    });
  }
});

最新更新