简体   繁体   中英

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.

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:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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