[英]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.