【问题标题】:disabling and enabling enter keypress event in javascript在javascript中禁用和启用输入按键事件
【发布时间】:2016-06-22 10:46:59
【问题描述】:
<!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'];


?>

在上面的代码中,我最初禁用了输入按键事件。我正在使用已经给出回车的条形码扫描仪。这让我可以在使用条形码扫描仪扫描第一个输入字段后专注于下一个输入字段。但是,我希望在第二个字段通过扫描仪输入数据时提交表单。我如何实现这一目标?

【问题讨论】:

    标签: javascript php jquery


    【解决方案1】:

    首先在id为j

    的input标签中添加oninput函数
    <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
    }
    

    【讨论】:

    • 嘿,但是有一个小错误。问题是第二个字段一次性输入条形码并提交表单,但如果我手动输入输入,除了第一个字符外,它不接受输入值。
    • 已修复!对 clickSubmitButton() function-function clickSubmitButton(){ $(document).keypress( function(event){ if (event.which == '13') { document.getElementById("submitbutton").click( ); } }); }
    • 不错。在您提到使用扫描仪输入的问题中。这就是我没有包含按键的原因。
    【解决方案2】:

    兼容多个输入的解决方案是专注于下一个,直到没有更多输入为止。

    另外,您不需要提交按钮。但你可以离开它。 此处摘录:

    $("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>

    【讨论】:

    • 嘿!当我在这里运行代码 sn-p 时它可以工作,但是当我在本地机器上运行它时它不工作。我用完整的代码编辑了我的帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 2013-09-10
    • 1970-01-01
    • 2014-09-17
    相关资源
    最近更新 更多