Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent form input to reload a page when receiving `Enter` key

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>
like image 750
thor Avatar asked Dec 08 '14 18:12

thor


People also ask

How do you prevent auto reload when Enter key in input field in React?

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?

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”); });

How do you disable enter submit in form?

You can also use javascript:void(0) to prevent form submission.


2 Answers

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

like image 128
Bhaskara Avatar answered Oct 12 '22 13:10

Bhaskara


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/

like image 20
Will Avatar answered Oct 12 '22 13:10

Will