Jump to content

[jQuery] How to check which form button was clicked after submit


noobstar

Recommended Posts

Hi Everyone :)

 

This has me rather puzzled. I've checked numerous websites to no avail and threw at it all I could muster without any luck. All I'm after is basically to check which submit button within a form has been clicked i.e. add user, delete user, update user blablabla

 

I have two pages test.html and test.php.

 

test.html

<div id="feedback"></div>
<form class="user_form">
    <input type="text" name="name" />
    <input type="submit" name="add_user" value="Add User" />
    <input type="submit" name="delete_user" value="Delete User" />
</form>

 

test.php

<?php
    if ($_POST['add_user']) {
        echo "add user: ".$_POST['name'];
    }
    if ($_POST['delete_user']) {
        echo "delete user: ".$_POST['name'];
    }
?>

 

javascript/jquery

<script type="text/javascript">
$(document).ready (
    function() {
        $(".user_form").submit (
            function () {
                if () { // add_user is clicked
                    $.post("test.php", { add_user: $(this.add_user).val(), name: $(this.name).val()}, function(data) { $("#feedback").html(data); });
                }
                if () { // delete_user is clicked
                    $.post("test.php", { delete_user: $(this.delete_user).val(), name: $(this.name).val()}, function(data) { $("#feedback").html(data); });
                }
            }    
    }
);
</script>

 

 

If there is a better way of going about this problem please let me know :)

 

Thank you very much for any help! :)

Yea it would be a way of going about it however, what I failed to mention (sorry about that) is that there are multiple forms with the same name so i need to distinguish between the buttons pressed for each of those hence why I did as shown above.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.