2012-03-31 56 views
3

我有一個表單,有多個提交按鈕。一個用於更改數據庫中的數據,一個用於添加,另一個用於刪除。它看起來像這樣:jQuery(或只是JS)從多個表單提交按鈕在onSubmit函數

<form action="addform.php" method="post" id="addform" onSubmit="return validate(this)"> 
<select name="listings" id="listings" size="1" onChange="javascript:updateForm()"> 
<!-- Here I have a php code that produces the listing menu based on a database query--> 
</select> 
<br /> 
Price: <input type="text" name="price" id="price" value="0"/><br /> 
Remarks: <textarea name="remarks" wrap="soft" id="remarks"></textarea><br /> 
<input type="submit" value="Update Database Listing" name="upbtn" id="upbtn" disabled="disabled"/> 
<input type="submit" value="Delete Database Listing" name="delbtn" id="delbtn" disabled="disabled"/> 
<br /> 
<input type="submit" value="Add Listing to Database" name="dbbtn" id="dbbtn"/> 
<input type="button" value="Update Craigslist Output" name="clbtn" id="clbtn" onClick="javascript:updatePreview();"/> 
</form> 

表單中實際上有更多的元素,但沒關係。我想知道的是,對於我的驗證方法,我如何檢查點擊了哪個提交按鈕?

我希望它做到以下幾點:

function validate(form){ 
     if (the 'add new listing' or 'update listing' button was clicked'){ 
     var valid = "Are you sure the following information is correct?" + '\\n'; 
     valid += "\\nPrice: $"; 
     valid += form.price.value; 
     valid += "\\nRemarks: "; 
     valid += form.remarks.value; 
     return confirm(valid);} 
     else { 
        return confirm("are you sure you want to delete that listing"); 
     } 
    } 

我想一定是有辦法做到這一點比較容易?

回答

2

爲什麼不設置一個全局變量來指定最後一次點擊哪個按鈕?然後你可以在你的validate方法中檢查這個變量。喜歡的東西:

var clicked; 

$("#upbtn").click(function() {clicked = 'update'}); 
// $("#delbtn").click(function() {clicked = 'delete'}); 
// ... 

function validate(form) { 
    switch(clicked) { 
    case 'update': 
     break; 
      // more cases here ... 
    } 
} 
0

我認爲只需在每個按鈕上使用單擊事件並單獨處理它會更容易。

$(function() { 
    $('input[name=someName]').click(someFunc); 
}); 

function someFunc() { 
    // Your validation code here 
    // return false if you want to stop the form submission 
} 
1

可以,例如,附加一個單擊事件到每一個提交按鈕,將指針保存到它在一個變量或具有特定屬性/類標記(它的話,你將不得不刪除標記從事件處理程序中的所有其他提交按鈕),然後在提交回調中,您將知道哪個被點擊

0

您可以在窗體上隱藏字段並在單擊該按鈕時設置該字段的值,然後在你的驗證程序中選擇它。你可以使用jQuery來實現這一點,讓我知道如果你需要一個例子。

0

您可以使用與jQuery的ajax提交,你可以嘗試這樣的事:

$('form#addform input[type="submit"]').on('click',function(e){ 
     e.preventDefault(); 
     var current = $(this); //You got here the current clicked button 
     var form = current.parents('form'); 

     $.ajax({ 
      url:form.attr('action'), 
      type:form.attr('method'), 
      data:form.serialize(), 
      success:function(resp){ 
       //Do crazy stuff here 
      } 
     }); 
});