Search code examples
htmlreactjsformsbuttonpage-refresh

How to prevent the submit button from reloading the page, while keeping default form warnings?


I have a simple form to get a table's row/column numbers, with a button type = "submit" that reloads the page onClick .

I want to keep the warnings when the user enters an invalid value, since the inputs have a maximum/minimum number required, which is not possible with the return false; in the end of the onClick method, or event.preventDefault();

Any ideas how to do that?

This code is in JSX:

<form id="table_form">
   <label>how many rows ?</label>
   <input
     type="number"
     name="rows"
     min={min_tablerows}
     max={max_tablerows}
     required
     value={tablerows}
     onChange={onChangeHandeler} />
   <label>how many columns ?</label>
   <input
     type="number"
     name="columns"
     min={min_tablecolumns}
     required
     value={tablecolumns}
     onChange={onChangeHandeler} />
   <button
     type="submit"
     form="table_form"
     onClick={onClickHandeler}>
       <FontAwesomeIcon icon={faCheck} />
   </button>
</form>

Solution

  • You want to keep the default html warnings if I understand your question well. I would like to suggest the following:

    1. Firstly, you don't need to attach onClick event handler for the button because a button in an HTML form or with the type submit by default submits to the form it is contained.

    2. You can attach onSubmit event handler to the main form and in its callback function prevent the default behaviour.

    3. With this, html5 will handle any errors and prevent the form from even submitting in the first place. When it doesn't find any error, it will run the callback function attached to the form's event handler.

    So your code might be as follows:

    handleSubmit(e) {
    e.preventDefault();
    // Do what you like here
    
    e.target.submit(); // if you want to submit the forms
    }
    
    <form id="table_form" onSubmit={this.handleSumbit.bind(this)}>
       <label>how many rows ?</label>
       <input
         type="number"
         name="rows"
         min={min_tablerows}
         max={max_tablerows}
         required
         value={tablerows}
         onChange={onChangeHandeler} />
       <label>how many columns ?</label>
       <input
         type="number"
         name="columns"
         min={min_tablecolumns}
         required
         value={tablecolumns}
         onChange={onChangeHandeler} />
       <button
         type="submit">
           <FontAwesomeIcon icon={faCheck} />
       </button>
    </form>