I have a HTML5 form as follows, which is styled with Bootstrap3 and contains a range
input and a number
input. The two inputs are linked so that whenever I change the range
value, the number
input is updated and vice versa.
What's bothering me is that when I change the number
input value and hit the Enter
key, the whole web page reloads and this wipes out all other data loaded into the page with JavaScript.
My questions is, how can I change the HTML/code to disable this reloading behavior?
Thanks.
<form class="form-horizontal">
<div class="form-group">
<div class="col-xs-6">
<input type="range" class="policy_slider" name="demandRange" min="0.1" max="10" value="1" oninput="this.form.demandInput.value=this.value"/>
</div>
<div class="col-xs-1">
<input type="number" name="demandInput" min="0.1" max="10" value="1" step="any" oninput="this.form.demandRange.value=this.value"/>
</div>
</div>
</form>
To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() . The preventDefault method prevents the browser from refreshing the page when the form is submitted. Copied!
How do I stop page reload/refresh on hit back button? You have to detect browser back button event and pass as an input of the page you want do prevent URL reload that indicates you if you came from a back button click. this code: $(window). on('popstate', function(event) { alert(“pop”); });
You can also use javascript:void(0) to prevent form submission.
As there are already plain old JS solutions, my answer is based on JQuery. Also, Bootstrap JS requires Jquery. So try this:
$("form").keypress(function(e) {
//Enter key
if (e.which == 13) {
return false;
}
});
If you have multiple forms in your page use this :
$("#form_id").keypress(function(e) {
//Enter key
if (e.which == 13) {
return false;
}
});
where form_id
is the id specified to your form something like this: <form id="form_id">...</form>
Courtesy: http://www.paulund.co.uk/how-to-disable-enter-key-on-forms
Set the form submit to use javascript and "return false". Afterwards, you can use another function to do the actual submit.
<form class="form-horizontal" onSubmit="return false;">
JSFIDDLE: http://jsfiddle.net/biz79/m3veL3uh/
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