0

I have a question similar to this one, but I don't want the browser to submit the form when I press the "Enter" key. Instead, I have a form like the following:

<form id="google_inputs">

    <h1 class="theme-text">Find a Store</h1>

    <input type="text" id="origin-address" value=""><br>

    <input type="button" label="test" value="search stores" onclick="onGoogleDistanceSearch()"/>

    <input type="button" label="test" value="search stores using my location" onclick="onGoogleDistanceSearchWithCurrentLocation()"/>

<form/> 

I have JavaScript that will render the HTML when the buttons are pressed, and I don't want to cause a page refresh. I've Googled around and looked at similar posts, but nothing seems to address this. Is there an attribute that an input tag can take that will be something like:

<input type"executeJavaScriptDoNotRefreshPage()"/>

Like I said, I looked at the W3 page on inputs and didn't find anything.

Community
  • 1
  • 1
Sal
  • 3,179
  • 7
  • 31
  • 41
  • 2
    Listen to keydowns on `#origin-address`, and prevent default action, if `ENTER` (keycode 13) was pressed. – Teemu Feb 07 '14 at 21:25

1 Answers1

2

For a form, you want to intercept the "submit" event. When you intercept this, you can prevent it from submitting with the typical method (a page load to the action parameter) and instead replace it with something like a JavaScript form submit.

document.getElementById('google_inputs').addEventListener('submit', function(e) {
    e.preventDefault(); // stop the normal submit
    // put your alternative method here
});
samanime
  • 25,408
  • 15
  • 90
  • 139