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

我的表格如下:

  • I'll be in touch soon

我试图通过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; }); }); 

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

谢谢

你应该使用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(); } }) }) }) 

看看jQuery Form Plugin ,它有像ajaxSubmit()这样的方法来减少你的工作。

把你的javascript代码放入

 $(document).ready({ $('#contactForm').submit(function() { //Do stuff here }); }); 

提交使用onsubmit检查表单:

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

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

alert("email" + email)有效?

一定要把所有东西都换成$().ready({ /* your code */ }); 。 现在你的代码可能在加载文档的其余部分之前运行,因此,当它试图找到将事件绑定到的按钮时,它会失败并且事件不会被绑定到任何东西。

除了$('.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( 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() `并且传递没有事件处理程序实际上触发了表单的提交,这也适用于所有其他事件)。

希望这可以帮助!