使用回车键执行文本字段功能

时间:2016-10-16 13:23:05

标签: javascript html textfield keypress

我尝试使用的代码。请告诉我我做错了什么。我不是很擅长JavaScript,所以不要判断。

                                                          

<!-- Textfield with Floating Label -->

<form action="#">
  <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
    <input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(e)">
    <label class="mdl-textfield__label" for="userInput">Answer Here</label>
  </div>
</form>

<script>
    function handle(e){
        if(e.keyCode === 13){
            e.preventDefault(); // Ensure it is only this code that rusn
var input = document.getElementById("userInput").value;
    alert(input);
        }
    }
</script>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

你可能想要传递这个事件,而不仅仅是e

<input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(event)">

&#13;
&#13;
<form action="#">
    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(event)">
        <label class="mdl-textfield__label" for="userInput">Answer Here</label>
    </div>
</form>

<script>
    function handle(e) {
        if (e.keyCode === 13) {
            e.preventDefault(); // Ensure it is only this code that rusn
            var input = document.getElementById("userInput").value;
            alert(input);
        }
    }
</script>
&#13;
&#13;
&#13;

您最好使用addEventListener代替

document.getElementById('userInput').addEventListener('keypress', function(e) {
    if(e.keyCode === 13) {
        e.preventDefault();
        var input = this.value;
        alert(input);
    }
});