在表单上按Enter键时找到留在页面上的方法

时间:2014-02-07 21:03:57

标签: javascript html forms

我有一个类似于this的问题,但是当我按“Enter”键时,我不希望浏览器提交表单。相反,我有一个如下形式:

<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/> 

我有JavaScript,当按下按钮时会呈现HTML,我不想导致页面刷新。我用Google搜索并查看了类似的帖子,但似乎没有解决这个问题。是否存在输入标记可以采用的属性:

<input type"executeJavaScriptDoNotRefreshPage()"/>

就像我说的那样,我查看了W3 page on inputs and didn't find anything

1 个答案:

答案 0 :(得分:2)

对于表单,您希望拦截“submit”事件。拦截时,您可以阻止它使用典型方法(对动作参数加载页面)进行提交,而是将其替换为JavaScript表单提交。

document.getElementById('google_inputs').addEventListener('submit', function(e) {
    e.preventDefault(); // stop the normal submit
    // put your alternative method here
});