2014-10-16 78 views
1

我有一個簡單的表單,有一個複選框和3個提交按鈕。只有當三個按鈕中的一個被點擊時,複選框字段才需要打勾。下面是該表單的HTML:有多個提交按鈕的條件表單驗證

<form role="form" action="udpate.php" id="review" method="post"> 

<div class="checkbox"> 
<label class="checkbox"> 
<input type="checkbox" name="approved" value="approved"> 
</label> 
</div> 

<p>I have approved all changes and are happy to proceed</p> 

<button type="submit" class="btn btn-default" name="buttonType" id="Reject" value="Reject">Reject</button> 
<button type="submit" class="btn btn-default" name="buttonType" id="Pending" value="Pending">Pending</button> 
<button type="submit" class="btn btn-default" name="buttonType" id="Approve" value="Approve">Approve</button> 
</form> 

下面是一個使用jQuery的驗證插件腳本:

<script> 
    $().ready(function() { 
     $("#Approve").click(function() { 
      $("#review").validate(); 

     }); 
    }); 
</script> 

目前點擊任意3個按鍵的執行驗證,但我也只需要驗證用戶是否單擊批准按鈕。只有此時需要勾選複選框,否則如果可以留空。

是否有可能進行某種驗證,檢查點擊了哪個按鈕,然後在繼續之前檢查該複選框是否爲空,如果該按鈕已被點擊?

+0

你可以分享你與完成代碼? – Mayank 2014-10-16 12:59:01

+0

@Mayank我只是添加了一些更多的細節,包括JQuery驗證代碼,當點擊3個按鈕中的任何一個時,它正在運行 – user982124 2014-10-16 13:02:33

回答

2

添加一個ID,形成和複選框,例如: 「Form1的」, 「checkbox1」

<form id="form1" ...> 
    <input type="checkbox" id="checkbox1" ... /> 
    ... 
</form> 

然後jQuery的添加到當前代碼:

$('#form1 button[type="submit"]').click(function(e){ 
    e.preventDefault();        // this for prevent form from submit 

    if($(this).val() == "Approve"){     // check if third button was clicked 
     if($('#form1 #checkbox1').is(':checked')){ // check if checkbox is checked 
      $('#form1').submit();     // submit form 
     }else{ 
      // here paste your info code, that checkbox is not checked 
     } 
    }else{           // any other button 
     $('#form1').submit(); 
    } 
});