返回false;在jquery .each函数中不起作用

技能学习

在发布此问题之前,我尝试了StackOverflow,但没有找到答案。

所以,问题是,我有一个带有一些值的数组(假设4,6,7,8,10等)。我使用jquery的.each函数来提示警报消息。但是我的代码给了我一条警告消息,将其聚焦到所需的输入框并提交表单,并且不会“返回false”。我希望它在聚焦后返回false。

$(document).on('keypress','#create_invoice',function(){
$.each(newArr, function( i, l ){
//alert( "Index #" + i + ": " + l );
if($.trim($('#item_name'+l).val()).length == 0)
        {
          alert("Please Enter Item Name");
          $('#item_name'+l).focus();
         // return false; //if use this not work and submit form
        }
//return false; //if use this not work and submit form
});
//return false; if i use this then submit() not work
$('#invoice_form').submit();
});
杰丁·贤哲

返回false起作用,但是我认为如果返回false,您想要的是阻止表单提交。这种行为可以做到。

首先e在函数参数中放置一个,然后使用e.preventDefault();

接下来是使变量成为布尔值,该布尔值将确定您是否可以提交表单。在下面的代码中,我使用了var allowSubmit

试试下面的代码。

$(document).on('keypress', '#create_invoice', function(e) {
  e.preventDefault();

  // boolean variable
  var allowSubmit = true;

  $.each(newArr, function(i, l) {
    if ($.trim($('#item_name' + l).val()).length == 0) {
      alert("Please Enter Item Name");
      $('#item_name' + l).focus();

      // set the variable to false
      allowSubmit = false;
      return false;
    }
  });

  // check if we could submit the form
  if (allowSubmit) {
    $('#invoice_form').submit();
  }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章