如何在提交表单时调用 jquery 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8999210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:23:28  来源:igfitidea点击:

How do I call a jquery function on submitting a form?

jqueryajaxforms

提问by Mervin

I have a form which is given below :

我有一个表格,如下所示:

 <form method="post" id="contactForm" action="">
                <fieldset class="contactFieldset">
                    <ul>
                        <li>
                            <label for="contactName" class="leftLabel">*Name:</label>
                            <input type="text" name="contactName" id="contactName" class="contactInput required" value="" />

                        </li>
                        <p></p>
                        <li>
                            <label for="email" class="leftLabel">*Email:</label>
                            <input type="text" id="email" name="email" class="contactInput email required" value="" />
                        </li>
                      <span class="simple-success">I'll be in  touch soon</span>
                        <li>
                            <label for="subject" class="leftLabel">*Subject:</label>
                            <input type="text" name="subject" id="subject" class="contactInput required" value="" />
                        </li>
                        <p></p>
                        <li>
                            <label for="message" class="leftLabel">Message:</label>
                            <textarea rows="10" cols="40" id="message" name="message" class="contactTextarea required"></textarea>

                        </li>
                       <p></p>
                        <li>


                            <input type="image" src="images/submitbutton.png" alt="Submit button" name="submit_button" class="submit_button" id="submit_button">

                        </li>
                    </ul>
                </fieldset>
            </form>

I am trying to extract the data from this form via jquery so that I can pass it on to the php file and send an email but the jquery function is not being called on clicking the button.The code is given below:

我正在尝试通过 jquery 从此表单中提取数据,以便我可以将其传递给 php 文件并发送电子邮件,但在单击按钮时不会调用 jquery 函数。代码如下:

    $(function() {
  $('.error').hide();
  $('.simple-sucess').hide();

  $(".submit_button").click(function() {





        /*get the email value*/

        var email = $("input#email").val();
        var name = $("input#contactName").val();
        var subject = $("input#subject").val();
        var message=$("input#message").val();
    //  alert("email"+email);

/* Check if the email is good or bad */

var goodEmail = email.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\.arpa)|(\.asia)|(\.cat)|(\.int)|(\.jobs)|(\.tel)|(\.travel)|(\.xxx)|(\..{2,2}))$)\b/gi);
    apos=email.indexOf("@");dotpos = email.lastIndexOf(".");lastpos=email.length-1;
    var badEmail    = (apos<1 || dotpos-apos<2 || lastpos-dotpos<2);

/*If the email is bad ,display the error message*/

if (email=="" || !goodEmail || badEmail) {

        $("email").focus();
      return false;
    }


        var dataString = 'email='+ email + '\n Name='+ name+ '\n Subject='+ subject+ '\n message='+ message;
        alert (dataString);

        $.ajax({
      type: "POST",
      url: "mai.php",
      data: dataString,
      success: function() {
        $('.simple-sucess').fadeIn(100).show();
        $('.contact_form').fadeOut(100).hide();
        $('.simple_error').fadeOut(100).hide();


      }
     });
    return false;
    });
});

Any ideas on what I might be doing wrong ?

关于我可能做错了什么的任何想法?

Thanks

谢谢

回答by Rishav Rastogi

You should use a document.readyblock and don't use submit-buttonclick; instead use $.submit()

你应该使用document.ready块而不是submit-button点击;而是使用$.submit()

$(document).ready(function() {
  $("your form selector here").submit(function() {


    // do the extra stuff here
    $.ajax({
     type: "POST",
      url: "mail.php",
      data: $(this).serialize(),
      success: function() {
        $('.simple-sucess').fadeIn(100).show();
        $('.contact_form').fadeOut(100).hide();
        $('.simple_error').fadeOut(100).hide();

       }
    })

  })
})

Take a look at the jQuery Form Plugin, whic has methods like ajaxSubmit()to reduce your work.

看看jQuery Form Plugin,它有一些方法ajaxSubmit()可以减少你的工作。

回答by KMan

Put your javascript code in

把你的javascript代码放进去

$(document).ready({

   $('#contactForm').submit(function() {

      //Do stuff here

   }); 

});

回答by Wouter J

Use onsubmit for checking of a form is submitted:

使用 onsubmit 来检查表单是否已提交:

$('#contactForm').on('submit', function() {
  alert('You submitted the form!');
});

回答by Andrei Barsan

First off, try to debug your code - Chrome has a neat console built-in (Ctrl + Shift + J) and Firefox has the awesome FireBug addon. You can then use console.log("Message");anywhere to check if the function has reached that area.

首先,尝试调试您的代码 - Chrome 有一个简洁的内置控制台 (Ctrl + Shift + J),而 Firefox 有很棒的 FireBug 插件。然后您可以使用console.log("Message");任何地方来检查该功能是否已到达该区域。

Is that alert("email" + email)working?

alert("email" + email)行得通吗?

Be sure to wrap everything in $().ready({ /* your code */ });. Right now your code is probably being run beforethe rest of the document is loaded and, thus, when it tries to find the button to bind the event to, it fails and the event doesn't get tied to anything.

确保将所有内容都包装在$().ready({ /* your code */ });. 现在,您的代码可能正在加载文档的其余部分之前运行,因此,当它尝试找到将事件绑定到的按钮时,它会失败并且该事件不会与任何内容相关联。

Apart from $('.submit-button').click(...)you can use $('#contactForm').submit( function() { /* code that's now in the click handler */ }. This would make the code a little more fail-safe, in case you might want to rename or remove that button, or if you want to manually submit the form from a piece of code. (Running$('#contactForm').submit()` and passing no event handler actually triggers the submission of the form, this works for all other events too).

除了$('.submit-button').click(...)您可以使用$('#contactForm').submit( function() { /* code that's now in the click handler */ }. This would make the code a little more fail-safe, in case you might want to rename or remove that button, or if you want to manually submit the form from a piece of code. (Running$('#contactForm').submit()` 并且不传递任何事件处理程序实际上会触发表单的提交,这也适用于所有其他事件)。

Hope this helps!

希望这可以帮助!