![](/img/trans.png)
[英]async function to trigger both with the search button and by pressing the "enter" key on the keyboard in the input field
[英]Pressing enter key on input field triggers button click function
<form onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<!--input type="submit" value="Submit"-->
<button onclick="alert('button click')">click</button>
</form>
在輸入觸發按鈕 onclick 上按 enter,表單提交。 如何避免按鈕 onclick 觸發器。
在表單呈現后運行它
document.querySelector('input[name="fname"]').onkeydown=e=>{
if(e.key==='Enter')e.preventDefault();
//if you want form submission
document.querySelector('form').submit();
};
當您在表單中有一個按鈕時,它默認鍵入“提交”,這意味着表單中的第一個按鈕將具有由 ENTER 鍵觸發的 onclick 事件。 為了防止這種情況發生,只需將 type="button" 分配給按鈕,輸入鍵將不再影響它。
嘗試這個
<form onsubmit="myFunction()"> Enter name: <input type="text" name="fname" id="fname"> <.--input type="submit" value="Submit"--> <button onclick="alert('button click')" id="btn">click</button> </form> <script type="text/javascript"> var input = document;getElementById("fname"). input,addEventListener("keypress". function(event) { if (event.key === "Enter") { event;preventDefault(). document.getElementById("btn");click(); } }); </script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.