【问题标题】:Detect type of submit, if it was by enter key or button click检测提交类型,如果是通过输入键或按钮单击
【发布时间】:2013-06-26 20:04:25
【问题描述】:

我有以下代码:

    <head>
        <script language="javascript">
            function subimiti(event){
                alert("Tipo do submit: "+event);
            }
        </script>
    </head>
    <body>
        <form id="f1" name="form1" onsubmit="subimiti(event)" action="http://www.google.com">
            <input type="text" id="meuId" value="Teste"/>
            <input id="butao" type="submit" value="Subimeta u fórmi trem bão!!"/>
        </form>

在我的 JavaScript 函数中,我想检测导致表单提交的事件。如果是通过我的文本字段中的回车键,或者是通过单击按钮。

【问题讨论】:

标签: javascript html forms


【解决方案1】:

由于当有提交按钮时 keypress 事件会触发 click 事件,所以我能想到的唯一解决方法是改用 type=button。

纯 JavaScript (Fiddle):

<form id="f1" name="form1" action="" onsubmit="subimiti(this)" method="POST">
  <input type="text" id="meuId" value="Test" onkeypress="setEvent(event)"/>
  <input id="butao" type="button" onclick="setEvent(event)" value="Subimeta u formi trem bao!!"/>
</form>

function subimiti(form)
{
  event.preventDefault();
  alert(form.getAttribute('event'));   

}

function setEvent(event)
{
 if(event.type == 'click')
 {
   document.form1.setAttribute('event','click');
   subimiti(document.form1);
 }
 else if (event.keyCode == 13)
 {
   document.form1.setAttribute('event','keypress');
 }
}

使用 jQuery(我认为更简洁/更简单的代码):

$(function(){
  $('form').submit(function(){
    alert($(this).attr('event'));
  });

  $("input#butao").on('click', function(e) {
    $("form").attr("event", "click").submit();
  });      

  $("input").on('keypress', function(e) {
    if (e.which == 13)
    {
      $("form").attr("event", "keypress");
    }
  });            
}); 

只有 butao 有一个点击监听器,任何输入都输入监听器。

<form id="f1" name="form1" action="">
  <input type="text" id="meuId" value="Teste"/>
  <input id="butao" type="button" value="Subimeta u formi trem bao!!"/>
</form>

Fiddle(将 preventDefault 添加到 fiddle 以便您无需实际提交即可看到结果)

【讨论】:

  • +1 : input[type=submit] 将始终触发两个事件(clickenter)。很好的解决方法,但是您只是忘记添加它使用 jQuery(OP 在他的问题中没有 jQuery 标签)
猜你喜欢
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 2014-06-29
  • 2013-06-22
  • 2017-12-28
相关资源
最近更新 更多