填写表格并按回车后调用功能

时间:2014-03-02 21:40:31

标签: javascript

在下面的脚本中

<html>
 <body>
    <form>
        First Name: <input type="text" id="myText" maxlength="30" >
    </form>
    <button onclick="procesText()">get name</button>

    <script>
    function procesText()
    {
      var y = document.getElementById("myText");
      alert(y.value);
      y.value="";
    }
    </script>

 </body>
</html>

我想调用函数procesText不是通过单击get name button,而是在我用文本填充输入时单击enter。如何实现?

2 个答案:

答案 0 :(得分:1)

HTML:

<form id="myform">
    First Name: <input type="text" id="myText" maxlength="30" >
</form>

JS :(如果你想将表格发送到te服务器)(Demo

document.getElementById('myform').onsubmit = procesText;

JS :(如果您不想将表单发送到te服务器)(Demo

document.getElementById('myform').onsubmit = function(e) {
    procesText();
    e && e.preventDefault && e.preventDefault();
    return false;
}

答案 1 :(得分:1)

只需删除按钮,调用onsubmit上的函数,并阻止它提交:

<form onsubmit="return procesText()">
    First Name: <input type="text" id="myText" maxlength="30" />
</form>
<script>
    function procesText() {
        var y = document.getElementById("myText");
        alert(y.value);
        y.value = "";
        return false;
    }
</script>

小提琴 Fiddle