简体   繁体   English

如何在单击按钮并按 Enter 时启动 jquery 功能

[英]How can I start a jquery function on clicking a button and on pressing enter

I have a function that sends some data from a form using Ajax.我有一个使用 Ajax 从表单发送一些数据的函数。

To prevent the form from posting it without Ajax I use preventDefault();为了防止表单在没有 Ajax 的情况下发布,我使用preventDefault(); this also stops the form from submitting when pressing enter .这也会在按下enter时阻止表单提交。

How can I make sure the function below is started when clicking the button (as it is now) and also when pressing the enter button?我如何确保在单击按钮时(就像现在一样)以及按下enter按钮时启动下面的功能?

jQuery: jQuery:

$("body").on("click",".login-button",function(e){
e.preventDefault();
    loginform = $(".login-form").serialize();

    $.ajax({
     type:'post',
     url:"includes/inloggen.php",
     data:({loginform: loginform}),
     success:function(data){
         var obj = JSON.parse(data);

         var arrayspot = 0;
         for (var i = 0; i < obj.length; i++) {
             var status = obj[i].status;
             var field = obj[i].field;
             if(status == 'error'){
                    var message = obj[i].message;
                    $( 'input[name="' + field + '"]' ).parent().addClass('invalid-input');
                    var errorveld = $( 'input[name="' + field + '"]' ).parent();
                    $( 'input[name="' + field + '"]' ).parent().next('.inputerror').remove();
                    errorveld.after('<div class="inputerror"><i class="fas fa-arrow-up"></i> ' + message + '</div>');
             }else if(status == 'success'){
                    $( 'input[name="' + field + '"]' ).parent().next('.inputerror').remove();
                    $( 'input[name="' + field + '"]' ).parent().removeClass('invalid-input');
             }
             var arrayspot = parseInt(i);
         }
         if(obj[arrayspot].totalstatus == 'error'){
             $( "#loginresult" ).removeClass('positiveresult');
             $( "#loginresult" ).show().empty().append( obj[arrayspot].totalmessage );
         }else if(obj[arrayspot].totalstatus == 'success'){
             window.location.replace("https://website.nl/new/");
         }
     }
 });
});

I've tried copying the entire function but this time start it on enter press but there must be another way with fewer lines of code?我试过复制整个函数,但这次在按下回车键时启动它,但必须有另一种代码行更少的方法吗? Without sending double ajax requests.不发送双重ajax请求。

You get this behaviour for free when you have your controls contained within a <form> .当您的控件包含在<form>时,您可以免费获得此行为。 From the context of your code using serialize() it appears this is already the case.从使用serialize()代码上下文来看,情况似乎已经如此。 As such you can simply amend your logic to listen for the submit event of the form instead of the click of the submit button.因此,您可以简单地修改逻辑以监听表单的submit事件,而不是click提交按钮。 Try this:尝试这个:

$("body").on("submit", ".login-form", function(e) {
  e.preventDefault();
  loginform = $(this).serialize();

  $.ajax({
    type: 'post',
    url: "includes/inloggen.php",
    data: {
      loginform: loginform
    },
    success: function(data) {
      var obj = JSON.parse(data);

      var arrayspot = 0;
      for (var i = 0; i < obj.length; i++) {
        var status = obj[i].status;
        var field = obj[i].field;
        var $errorveld = $('input[name="' + field + '"]').parent();

        if (status == 'error') {
          var message = obj[i].message;
          $errorveld.addClass('invalid-input');
          $errorveld.next('.inputerror').remove();
          $errorveld.after('<div class="inputerror"><i class="fas fa-arrow-up"></i> ' + message + '</div>');
        } else if (status == 'success') {
          $errorveld.next('.inputerror').remove();
          $errorveld.removeClass('invalid-input');
        }
        var arrayspot = parseInt(i);
      }
      if (obj[arrayspot].totalstatus == 'error') {
        $("#loginresult").removeClass('positiveresult').show().empty().append(obj[arrayspot].totalmessage);
      } else if (obj[arrayspot].totalstatus == 'success') {
        window.location.replace("https://website.nl/new/");
      }
    }
  });
});

Also note that I tidied the logic a little by removing the unnecessary () around the data property and also caching the $('input[name="' + field + '"]').parent() selector.另请注意,我通过删除data属性周围不必要的()并缓存$('input[name="' + field + '"]').parent()选择器来稍微整理逻辑。

Finally, if the MIME type of the response is set correctly you shouldn't need to manually call JSON.parse(data)最后,如果响应的 MIME 类型设置正确,则不需要手动调用JSON.parse(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM