表单按钮提交触发功能

时间:2013-09-10 20:14:24

标签: jquery jquery-selectors

我的表单中包含多个文本输入和一个提交按钮。在提交时,我想触发一个功能,但我遇到了困难。

表格如下,我尝试了以下内容:

$('#contactForm input.btn_submit').click(function(event){ // function here

$('#contactForm input.btn_submit').click(function(event){ // function here

$('#contactForm.report_row.input.btn_submit').click(function(event){ // function here

但没有运气。

以下是表格:

<form action="https://example.com/index.php/contact" method="post" id="contactForm" name="contactForm">
    <input type="hidden" />

    <div class="report_row">
        <strong>Your Name:</strong><br />
        <input type="text" id="contact_name" name="contact_name" value=""  class="text" />              </div>
    <div class="report_row">
        <strong>Your Email Address:</strong><br />
        <input type="text" id="contact_email" name="contact_email" value=""  class="text" />                </div>
    <div class="report_row">
        <strong>Your Phone Number:</strong><br />
        <input type="text" id="contact_phone" name="contact_phone" value=""  class="text" />                </div>
    <div class="report_row">
        <strong>Message Subject:</strong><br />
        <input type="text" id="contact_subject" name="contact_subject" value=""  class="text" />                </div>                              
    <div class="report_row">
        <strong>Message:</strong><br />
        <textarea id="contact_message" name="contact_message"  rows="4" cols="40" class="textarea long" ></textarea>                </div>      
    <div class="report_row">
        <strong>Security Code:</strong><br />
        20 + 9 = <br />
        <input type="text" id="captcha" name="captcha" value=""  class="text" />                </div>
    <div class="report_row">
        <input name="submit" type="submit" value="Send Message" class="btn_submit" />
    </div>
</form>

如何在点击最后的提交按钮时触发某个功能?

4 个答案:

答案 0 :(得分:2)

不清楚“我遇到困难”是什么意思。

可能是您没有停止表单提交,因此您可以运行您的功能。在这种情况下,您需要使用.preventDefault()。我建议你也将你的函数包装在一个就绪函数中,这样当你的页面加载了所有的html时你的代码就会运行。

像:

$('#contactForm input.btn_submit').click(function(event){ 
    event.preventDefault();
    // rest of code
    alert('Working!');
});

演示here

答案 1 :(得分:1)

怎么样

$('form').submit(function(){// ...
                                    });

答案 2 :(得分:1)

只要提交表单,就会触发以下内容:

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

答案 3 :(得分:1)

也许你可以尝试做这样的事情:

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

}); 

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

});