简体   繁体   English

如果未填写必填字段,如何防止提交表单上的函数调用?

[英]How to prevent function call on submit form if required fields are not filled out?

I have form with required inputs, it actually sees empty field and shows message, but it calls function from submit button我有需要输入的表单,它实际上看到空字段并显示消息,但它从提交按钮调用函数

<form action="">
    <input required id="1" type="text">
    <button type="submit" onclick="calculate()">Calculate</button>
</form>

An onclick listener will run whenever the button is clicked, no matter what.无论何时单击按钮, onclick侦听器都会运行。

You want the function to run only when the form starts to be submitted, so attach a submit listener to the form instead:您希望该函数仅在表单开始提交时运行,因此将submit侦听器附加到表单:

<form action="" onsubmit="calculate()">
    <input required id="1" type="text">
    <button type="submit">Calculate</button>
</form>

 const calculate = (e) => { console.log('calculating'); }
 <form action="" onsubmit="calculate()"> <input required id="1" type="text"> <button type="submit">Calculate</button> </form>

If at all possible, it would be much better to attach the event listener properly using Javascript instead of an inline HTML attribute:如果可能的话,最好使用 Javascript 而不是内联 HTML 属性正确附加事件侦听器:

document.querySelector('form').addEventListener('submit', calculate);

 const calculate = (e) => { e.preventDefault(); console.log('calculating'); }; document.querySelector('form').addEventListener('submit', calculate);
 <form action=""> <input required id="1" type="text"> <button type="submit">Calculate</button> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何防止JavaScript form.submit()忽略必填字段 - How to prevent JavaScript form.submit() from ignoring required fields 如何创建需要填写的条件字段 - How to create conditional fields that are required to be filled out 即使未填写必填字段,我是否可以在超时时提交表单 - Can I submit form on timeout even if required fields are not filled GTM - 表单提交时的Fire标记(仅当填写了必填字段时) - GTM - Fire tag on form submit (only if required fields are filled) 如何仅在使用 bootstrap 填写所有必需的 attr 字段后才提交表单? - How to submit a form only if all the required attr fields are filled using bootstrap? 未填写必填字段时停止提交表单 - Stop form submission when the required fields have not been filled out 如何防止提交但仍验证必填字段? - How to prevent submit but still validate required fields? 仅在提交表单之前填写必填字段的情况下,才能创建模式 - How to create a modal only if the required fields are filled out before submitting form 如何检查表单中所有必填字段的填写时间? - How can I check when all of the required fields of a form has been filled out? 使用Redux表单,如果未填写任何字段,如何禁用提交按钮? - Using Redux Form, how can I disable the submit button if no fields have been filled out?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM