我有一个带有两个文本框的表单,一个选择下拉框和一个单选按钮。当按下enter键时,我想调用JavaScript函数,但当我按下它时,表单就提交了。

当按下回车键时,如何防止表单被提交?


当前回答

下面是如何使用JavaScript来完成它:

//in your **popup.js** file just use this function var input = document.getElementById("textSearch"); input.addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { alert("yes it works,I'm happy "); } }); <!--Let's say this is your html file--> <!DOCTYPE html> <html> <body style="width: 500px"> <input placeholder="Enter the text and press enter" type="text" id="textSearch"/> <script type="text/javascript" src="public/js/popup.js"></script> </body> </html>

其他回答

下面的代码将在整个页面上添加ENTER键监听器。

这在带有单个操作按钮的屏幕中非常有用,例如登录,注册,提交等。

<head>
        <!--Import jQuery IMPORTANT -->
        <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

         <!--Listen to Enter key event-->
        <script type="text/javascript">

            $(document).keypress(function (e) {
                if (e.which == 13 || event.keyCode == 13) {
                    alert('enter key is pressed');
                }
            });
        </script>
    </head>

已在所有浏览器上测试。

<div class="nav-search" id="nav-search">
        <form class="form-search">
            <span class="input-icon">
                <input type="text" placeholder="Search ..." class="nav-search-input" id="search_value" autocomplete="off" />
                <i class="ace-icon fa fa-search nav-search-icon"></i>
            </span>
            <input type="button" id="search" value="Search" class="btn btn-xs" style="border-radius: 5px;">
        </form>

</div>

<script type="text/javascript">
    $("#search_value").on('keydown', function(e) {
        if (e.which == 13) {
             $("#search").trigger('click');
            return false;
        }
    });
    $("#search").on('click',function(){
        alert('You press enter');
    });
</script>

在用户定义的函数中使用event.preventDefault()

<form onsubmit="userFunction(event)"> ...

函数userFunction (ev) { 如果(! event.target.send.checked) { console.log('form NOT submit on "Enter" key') ev.preventDefault (); } } 打开chrome控制台>网络选项卡查看 <form onsubmit="userFunction(event)" action="/test.txt"> . <input placeholder="type and press Enter" /><br> . <input type="checkbox" name="send" /> submit on enter > < /形式

<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">

在HTML页面中添加此代码…它会使……输入按钮. .

下面是如何使用JavaScript来完成它:

//in your **popup.js** file just use this function var input = document.getElementById("textSearch"); input.addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { alert("yes it works,I'm happy "); } }); <!--Let's say this is your html file--> <!DOCTYPE html> <html> <body style="width: 500px"> <input placeholder="Enter the text and press enter" type="text" id="textSearch"/> <script type="text/javascript" src="public/js/popup.js"></script> </body> </html>