user982124
user982124

Reputation: 4610

Conditional Form Validation with multiple submit buttons

I have a simple form that has a single checkbox and 3 submit buttons. The checkbox field is required to be ticked only if one of the three buttons is clicked. Here's the html for the form:

<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>

Here's a script that uses the jQuery validation plugin:

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

        });
    });
 </script>

At the moment clicking any of the 3 buttons performs the validation, but I need it to only validate if the user clicks the Approve button. Only then is the checkbox required to be ticked, otherwise if can be left blank.

Is it possible to have some kind of validation that checks which button was clicked and then also checks that the checkbox is not empty if that button has been clicked before proceeding?

Upvotes: 1

Views: 2002

Answers (1)

rgwsk65
rgwsk65

Reputation: 309

Add an ID to form and checkbox, for example: "form1", "checkbox1"

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

Then add jQuery to current code:

$('#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();
    }
});

Upvotes: 2

Related Questions