2012-01-27 237 views
1

我想呼籲一下形式的一個按鈕jQuery的功能,在這裏調用一個jQuery查詢是我使用上點擊一個按鈕

按鈕代碼代碼:

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

形式出發代碼

<form method="post" action="" id="contactForm"> 

jQuery代碼

<script type="text/javascript"> 
$(document).ready(function() { 

    //if submit button is clicked 
    $('input[name=submit_button]').submit(function() {  


alert("testing") 

..... 

我試過所有的提交按鈕來調用jquery函數但無濟於事(我嘗試使用submit()或click())。

什麼可能我是做錯了(此表格位於HTML頁)

編輯:剛插入的jQuery函數我試圖運行的代碼,我實際上是想利用調用PHP腳本AJAX,然後隱藏表單如果表單提交成功

$(document).ready(function() { 

    //if submit button is clicked 
    $('#submit_button').submit(function() {   

      alert("testing") /*get the email value*/ 

var name = $('input[name=name]'); 
     var email = $('input[name=email]'); 
     var subject= $('input[name=subject]'); 
     var message = $('textarea[name=message]'); 


data = 'name=' + name.val() + '&email=' + email.val() + '&subject=' + 
     subject.val() + '&message=' + encodeURIComponent(message.val()); 


     //disabled all the text fields 
     $('.text').attr('disabled','true'); 



     //start the ajax 
     $.ajax({ 
      //this is the php file that processes the data and send mail 
      url: "mai.php", 

      //GET method is used 
      type: "POST", 

      //pass the data   
      data: data,  



      //success 
      success: function() {    

        $('.contact_form').fadeOut('slow');     

        //show the success message 
        $('.simple-sucess').fadeIn('slow'); 

       //if process.php returned 0/false (send mail failed) 
       } 



     }); 

     //cancel the submit button default behaviours 
     return false; 
    }); 
}); 
</script> 
+0

相關:http://stackoverflow.com/questions/5411198/on-click-with-button-in-jquery – 2012-01-27 01:53:58

回答

2

好提供一個成功的消息,該名稱應該是在引號:

$('input[name="submit_button"]') 

http://api.jquery.com/attribute-equals-selector/

value [..]屬性值。報價是強制性的。

不管怎樣,您應該可能使用ID。我不認爲你打算在按鈕上使用.submit。嘗試使用.click代替,或在表單上使用.submit

+0

此外,您可能需要返回true/false取決於你打算如何處理onsubmit處理程序的默認行爲 – thescientist 2012-01-27 01:53:43

+0

我試過使用,但沒有用,代碼是$(#submit_button).submit(function() – 2012-01-27 01:53:58

+0

您的意思是$('#submit_button')'? – 2012-01-27 01:54:38

0

你有沒有嘗試過這樣的代碼:

<script type="text/javascript"> 

    $(document).ready(function() { 
     //if submit button is clicked 
     $('#submit_button').submit(function() {  
     alert("testing"); 
     }); 
    }); 

</script> 
+0

,謝謝我試過了,但它只是刷新頁面 – 2012-01-27 02:22:48

+0

您的目標是提交表單輸入按鈕? – jeff 2012-01-27 02:31:21

+0

我剛剛更新了問題,以顯示我實際上正在嘗試做什麼,我試圖在jQuery中調用一個將提交表單數據到php郵件表單的ajax函數。郵件表單工作正常..只是這個函數這是驅使我堅果 – 2012-01-27 02:36:40

0

你爲什麼不嘗試使用類型的按鈕,而不是提交?如果您想在單擊按鈕後刷新頁面,則可以在腳本結尾處添加返回true。 =)