php - one form, multiple submits with onclick event

481 views Asked by At

I have a form with two submit buttons, in code behind I got the values from each submit, but the problem is when I add a javascript onclick event on each submit, when I try to retrieve the values in PHP I get nothing. I get the input submit values only when I don't use an event.

I don't get the input submit values from this code:

<input type="submit" id="send1" value="Send1" name="sub1" onclick="validate1();"/>
<input type="submit" id="send2" value="Send2" name="sub2" onclick="return validate2();"/>

This one works:

<input type="submit" id="send1" value="Send1" name="sub1" />
<input type="submit" id="send2" value="Send2" name="sub2" />
2

There are 2 answers

1
heliosk On BEST ANSWER

I find a solution. If a value of a disabled button cannot be posted, then I'm just adding a hidden field with some value identifying the submit button clicked.

<input type="hidden" id="my_post_value" name="my_post_value"/>
1
Saeven On

Here's a quick setup to do what you want https://jsfiddle.net/d090618g/

Your HTML

 <form id="theform">

    <input type="submit" name="s1" /> 
    <input type="submit" name="s2" />

    <input type="hidden" name="clicked" id="clicked" />

</form>    

<div id="result"></div>

Quick JQuery

var $form    = $("#theform");
var $clicked = $("#clicked");

$form.find( "input[type='submit']").click( function(){
    $clicked.val( $(this).attr('name') );
});

$form.submit( function( e ){
    e.preventDefault();

    switch( $clicked.val() ){

        case 's1':
            alert( "Do thing 1" );
            return;

        case 's2':
            alert( "Do thing 2" );
            return;
    }

    //post your form to PHP here        

    $("#result").html( $clicked.val() );

});