javascript - 停止在函数中提交表单 - jquery/javascript

标签 javascript jquery html forms

发布的代码可能不一致,因为我正在继续某人的工作,并尽可能不进行太多更改。 无论如何,有这种形式可以供其他人输入值。 提交后,如果输入字段为空,则会弹出警报并停止提交表单。

我尝试在输入字段为空但表单仍提交时使用 return false;event.preventDefault();

尝试缩短这个时间,因为剧本实在太糟糕了

只是一个简单的表格

<form action="cart.php" method="post" name="ordering" id="ordering" onsubmit="addDesc();">
    <button type="submit" class="add-to-cart" alt='Add this product to your shopping cart now.'>Add to Cart <span class="fa fa-cart-plus"></span></button>
  </form>

函数

function addDesc(desc){
// some variables to be passed when form submits
// an $.each function to loop through something
    //inside the loop it'll push input values into an array called checkEmpty
  if(jQuery.inArray("", checkEmpty) !== -1){
    alert('Please Do not leave any input fields empty.');
    return false;
  }else{
   //some outputs        
  }
}

return false 是我第一次尝试,但表单仍然提交。 我什至尝试过类似的事情

$('.add-to-cart').on('click', addDesc(event));

在 addDesc() 内部,我使用了 event.preventDefault(),而不是 return false

提前致谢。

最佳答案

非常简单。只需在调用函数 onsubmit 之前添加一个 return 即可:

<form action="cart.php" method="post" name="ordering" id="ordering" onsubmit="return addDesc();">

应该可以解决问题(返回truefalse将发送表单或阻止提交)。

关于javascript - 停止在函数中提交表单 - jquery/javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32214592/

相关文章:

javascript - 未使用的属性(property)下降?

html - 打印您看到的网页的最佳方式是什么?

html - 从媒体打印屏幕中删除链接引用

javascript - 单击按钮重置下拉选择器

javascript - UTC 问题,Flot X 轴时间错误

javascript - 如何将单选按钮与输入文本字段绑定(bind)?

javascript - Jquery - 在没有直接输入的情况下从多个输入字段中获取总数

php - 将 PHP 输出传递给 jQuery

c# - JSON 字符串不填充对象的基本属性 (MVC 4)

jquery - 附加的文本字段不会换行