javascript - 使用 Enter 键执行文本字段功能

标签 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>

最佳答案

您可能想要传递事件,而不仅仅是e

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

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

最好使用 addEventListener 代替

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

关于javascript - 使用 Enter 键执行文本字段功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40070740/

相关文章:

javascript - 将可聚焦控件限制在当前对话框中的最佳方法是什么?

javascript - 获取同一文件中 PHP 变量中选择框的 HTML 值

html - 防止可折叠导航栏包裹在图像下?

html - 向可滚动的 div 添加线性渐变

ios - Swift 和 SwiftUI 从 TextField 字符串绑定(bind)到模型已发布的可选 Integer 属性

javascript - document.getElementById ('inner' ).innerHTML ="message"; IE 给我一个错误

javascript - 不知道图片类型时的Base64图片SRC

HTML 表单,如何垂直对齐和居中输入字段?

iOS:文本字段现在将整个应用程序中的条目格式化为电话号码

reactjs - 我怎样才能使用一个主题来设置所有 material-ui 输入的样式,就好像它们有一个变体 ='outlined' 一样?