简体   繁体   English

在复选框更改时提交表单并保持内置浏览器验证

[英]Submit form on checkbox change and keep built-in browser validation

My form consists of text input and a checkbox.我的表单由文本输入和复选框组成。

The text input cannot be empty upon form submit, hence the required parameter.表单提交时文本输入不能为空,因此required参数。

I want to submit the form on each checkbox change and still keep this built-in validation.我想在每个复选框更改时提交表单,并仍然保留此内置验证。 Currently, if the text input is empty and I click the checkbox, it WILL submit.目前,如果文本输入为空并且我单击复选框,它将提交。

How can keep the validation on checkbox change?如何保持对复选框更改的验证?

 const Form = () => { const handleSubmit = (e: any) => { e.preventDefault() alert('submitted') } return ( <form onSubmit={handleSubmit}> <input type="text" required /> <input type="checkbox" onChange={(e) => handleSubmit(e)} /> <button type="submit">Submit</button> </form> ) } const root = document.getElementById('root') ReactDOM.render(<Form />, root)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

You can try to trigger the submit button, in this case the html5 validation should run:您可以尝试触发提交按钮,在这种情况下,html5 验证应该运行:

 const Form = () => { const handleSubmit = (e: any) => { e.preventDefault() alert('submitted') } const handleChange = (e: any) => { const btn = document.getElementById('btnSubmit'); btn.click(); } return ( <form onSubmit={handleSubmit}> <input type="text" required /> <input type="checkbox" onChange={(e) => handleChange(e)} /> <button id="btnSubmit" type="submit">Submit</button> </form> ) } const root = document.getElementById('root') ReactDOM.render(<Form />, root)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM