[英]how do i use an an enter key stroke to submit a username and password
我有一個工作正常的登錄按鈕,它可以讓用戶登錄等。但我也想讓用戶按 Enter 鍵登錄。 我該怎么做。我嘗試使用 onkeypress 進行測試,但沒有執行以下任何操作
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Username id="username" />
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="........" id="password" onkeypress=myFunction() /> //i just tried this myFunction() to see if it would give an alert but it doesnt
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-login" id="btnLogin">Log in</button>
</div>
</div>
</form>
function myFunction()
{ alert("button pressed")}
那么我如何使用回車鍵在 javascript 和 jquery 中提交我的請求
當您將input
放置在包含提交按鈕的form
元素中時,默認情況下您會獲得此行為。 要掛鈎它,請使用表單的submit
事件,如下所示:
$('form').on('submit', function(e) { e.preventDefault(); // only used to stop the form submission in this example console.log('form submitted'); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <div class="form-group"> <input type="text" class="form-control" placeholder="Username" id=" username" /> </div> <div class="form-group "> <input type="password" class="form-control" placeholder="........" id="password" /> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-login" id="btnLogin">Log in</button> </div> </form>
請注意,我修復了第一個input
placeholder
屬性之后缺少的"
。在所有屬性值之后您也不需要尾隨空格,因此我也刪除了它們。
首先,您需要將事件發送到myFunction()
函數並將 ID 添加到您的表單以手動添加提交:
HTML
<form id='myForm'>
<!-- form actions (etc..) -->
<input type="password" class="form-control" placeholder="........" id="password" onkeypress=myFunction(e) />
<!-- form actions (etc..) -->
</form>
現在在 ASCII 中,重新輸入代碼是13
您需要檢查的是當按下的鍵重新輸入時(13),然后您需要獲取事件鍵代碼並調用提交函數:
function myFunction(e)
var code = (e.keyCode ? e.keyCode : e.which);
{
if (code == "13")
{
//Calling the submit or clicking manually it
$( "#myForm" ).submit();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.