I have a form with an input for email.
<form action="." method="post">
<div id="email-wrapper">
<input type="text" placeholder="Your email" name="email" ref="email" onChange={this.handleChange}/>
</div>
<span class="signup-error">Please provide a valid email.</span>
</form>
....
....
<button id="next-btn" onClick={this.saveAndContinue}>Next</button>
When the button is pressed I validate with simple regex to confirm that its an email address, and this is working fine. However, if I press enter (key=13
), it directs to someother page and this is the error I see:
Cannot POST /
I thought this script would handle the problem, but it didn't:
handleChange = (event) => {
event.preventDefault();
var keyCode = event.keyCode || event.which;
if (keyCode == '13'){
console.log('enter pressed');
}
}
What's going on? How can I prevent redirection that occurs when I press enter key in an input field? Could you please help me. Thank you.
This is because the actions is done on the form when you hit enter. So you need to catch the action from the form and prevent defaults.
you can use the same event handler on onsubmit
of the form
<form action="." onsubmit={this.saveAndContinue} method="post">
....
Try handling the onKeyPress
event. You'll need to return false
when the Enter key is pressed in your handleChange
function. You'll need to return the return value in your handleChange
function in your event wireup; something like
<input type="text" onKeyPress="return handleChange(event)" />
In all, you can try:
<form action="." method="post">
<div id="email-wrapper">
<input type="text" placeholder="Your email" name="email" ref="email" onKeyPress={return this.handleChange(event)}/>
</div>
<span class="signup-error">Please provide a valid email.</span>
</form>
....
....
<button id="next-btn" onClick={this.saveAndContinue}>Next</button>
<script>
handleChange = (event) => {
event.preventDefault();
var keyCode = event.keyCode || event.which;
if (keyCode == '13'){
console.log('enter pressed');
return false;
}
}
</script>
First off handle the input fields onkeypress like so:
<input type="text" placeholder="Your email" name="email" ref="email" onkeypress="handleEnterKey(event)"/>
Then create the function handleEnterKey as follows:
function handleEnterKey(e){
if(e.keyCode == 13){ // enter pressed
try{
e.preventDefault ? e.preventDefault() : (e.returnValue = false);
//DO ALTERNATE ACTION RATHER THAN SEND ENTER
}catch(err){
console.log(err.message);
}
}
}
Also sometimes in older version of Internet Explorer and lesser known browsers the event.preventDefault() will not be sufficient to stop the enter key from propogating to parent so you can alternatively use:
event.stopPropagation();
Hope this helps.
try adding return false;
in front of your functions in your onClick attribute
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With