Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.