簡體   English   中英

在javascript中禁用和啟用enter keypress事件

[英]disabling and enabling enter keypress event in javascript

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>


$(document).keypress(
    function(event){
     if (event.which == '13') {

        event.preventDefault();

        $("#j").focus();


      }


});


</script>
</head>
<body>
<form id = "form1" action ='<?php echo $_SERVER['PHP_SELF']; ?>' method = "post">
    <input type = "text" name = 'i' id = 'i' autofocus>
    <input type = "text" name = 'j' id = 'j'>
    <input type = "submit" name = 'submit' value = 'submit'>
</form>

</body>
</html>

<?php


echo $_POST['i'];
echo $_POST['j'];


?>

在上面的代碼中,我最初禁用了回車鍵按下事件。 我正在使用條形碼掃描儀,它已經回收了。 這使我可以在使用條形碼掃描儀掃描第一個輸入字段后,將焦點對准下一個輸入字段。 但是,我希望在第二個字段通過掃描儀輸入數據時提交表單。 我該如何實現這一目標?

與多個輸入兼容的解決方案是關注下一個輸入,直到沒有更多輸入。

另外,您不需要提交按鈕。 但你可以離開它。 這里的片段:

 $("input[type='text']").keypress(function(e) { if (e.which != '13') { return; } e.preventDefault(); var next = $(this).next("input[type='text']"); if (next.length > 0) { next.focus(); } else { $("#form1").submit(); } }); $("#form1").on('submit', function() { console.log("submitted !"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="form1" action="/my/url" method="post"> <input type="text" name='i' id='i' autofocus> <input type="text" name='j' id='j'> <input type="submit" name='submit' value='submit'> </form> 

首先函數添加oninput與ID j中輸入標簽

<input type = "text" name = 'j' id = 'j' oninput="clickSubmitButton()">

然后提供id提交按鈕。

<input type = "submit" name = 'submit' id='submitbutton' value = 'submit'>

最后添加javascript代碼自動點擊按鈕。

function clickSubmitButton(){
document.getElementById("submitbutton").click(); //id of the submit button to be clicked
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM