I want to submit the form to Node.js, but when ever I press the submit button the page reloads, so I console.log()
to make sure it’s really going inside that function, but it did not work it did not log in the console and I tried to do a alert
but it also not working, and nothing working even the name of the function in onSubmit
listener is correct.
Here is the code (the full code is bit big and it can create problem in understanding the code so I am giving just the main form code and the onSubmit
listener function).
Functions:
const AddProducts = async (e) => {
alert('asdf');
e.preventDefault();
}
const editTheProduct = async (e) => {
e.preventDefault();
}
The form code:
<form method='POST' onSubmit={props.addOrEdit === 'ADD' ? AddProducts : editTheProduct} className='AdminProductEdit'>
<div className='LoginInputs'>
<input type='text' name='name' required value={props.addOrEdit === 'ADD' ? newProduct.name : ''} onChange={handleInput} />
<span className="LoginInputSpan">Product Name</span>
</div>
<div className='LoginInputs'>
<input type='text' name='price' required value={props.addOrEdit === 'ADD' ? newProduct.price : ''} onChange={handleInput} />
<span className="LoginInputSpan">Price</span>
</div>
<div className='LoginInputs' style={{ padding: '0', border: 'none', height: 'auto' }}>
<textarea placeholder='Description' />
</div>
<div className="LoginBtn">
<button type="submit" style={{ width: '200px' }}>SAVE CHANGES</button> // the Submit button
</div>
</form>
4
Answers
it worked as when I separately add the eventListner to the form like this
and remove the `onSubmit``` listener from the form like this
this is
j|tsx
it’s not vue so it’s pretty annoying you need to make it clear it’s a function for the compiler to work correctly:Write the prevent default as the first line of form and it should work
Another thing is make sure that there are no other buttons who have type as submit or button with no type at all. Make sure to give
type=button
explicitly for normal buttons within the formFirst check the
props
have valid data by,