tags:

views:

394

answers:

9

I have a very simple form with a name field and two submit buttons: 'change' and 'delete'. I need to do some form validation in javascript when the form is submitted so I need to know which button was clicked. If the user hits the enter key, the 'change' value is the one that makes it to the server. So really, I just need to know if the 'delete' button was clicked or not.

Can I determine which button was clicked? Or do I need to change the 'delete' button from a submit to a regular button and catch its onclick event to submit the form?

The form looks like this:

 <form action="update.php" method="post" onsubmit="return checkForm(this);">
    <input type="text" name="tagName" size="30" value="name goes here" />
    <input type="hidden" name="tagID" value="1" />
    <input type="submit" name="submit" value="Change" />
    <input type="submit" name="submit" value="Delete" />
 </form>

In the checkForm() function, form["submit"] is a node list, not a single element I can grab the value of.

A: 

Name the delete button something else. Perhaps name one SubmitChange and name the other SubmitDelete.

zincorp
This wouldn't help. As far as I observe, the value of the submit button isn't transmitted when the form is submitted.
David Parunakian
The value of the submit button is transmitted when pressed/clicked. If isn't present the default submit button was pressed, probably by pressing enter on one of the form entry fields.
Pentium10
How does the name change help me determine which was clicked? I need to know in javascript, not on the update.php page.
Scott Saunders
That's true. My answer merely helps you with the conflicting names. What you'll probably want to do is change each submit button to a regular type="button" button. Assign an onclick to each of those, and inside their respective onclick handlers call document.forms["formname"].submit();
zincorp
@zincorp: I don't recommend this - it would break the page if JS is disabled
Christoph
A: 

Give each of the buttons a unique ID such as

<input type="submit" id="submitButton" name="submit" value="Change" />
<input type="submit" id="deleteButton" name="submit" value="Delete" />

I'm not sure how to do this in raw javascript but in jquery you can then do

$('#submitButton').click(function() {
  //do something
});
$('#deleteButton').click(function() {
  //do something
});

This says that if submitButton is clicked, do whatever is inside it. if deleteButton is clicked, do whatever is inside it

Catfish
How does the id help?
Scott Saunders
You can grab elements based on their id's and perform operations on them.
Catfish
Will one of those operations tell me whether the button was clicked?
Scott Saunders
I edited my answer to explain
Catfish
doesn't your jQuery code need a # in front of the IDs?
Renesis
@Renesis your right. Edited again.
Catfish
A: 

Right now you've got the same problem as you would a normal text input. You've got the same name on two different elements. Change the names to "Change" and "Delete" and then determine if either one of them were clicked by applying an event handler on both submits and providing different methods. I'm assuming you're using pure JavaScript, but if you want it to be quick, take a look at jQuery.

What you need is as simple as following what's on w3schools

Michael Stone
+2  A: 

You could also use the onclick event in a number of different ways to address the problem.

For instance:

<input type="submit" name="submit" value="Delete" 
       onclick="return TryingToDelete();" />

In the TryingToDelete() function in JavaScript, do what you want, then return false if do not want the delete to proceed.

Glen Little
+1  A: 
<html>
<script type="text/javascript">
var submit;
function checkForm(form)
{
alert(submit.value);
return false;
}

function Clicked(button)
{
  submit= button ;
}
</script>
<body>
 <form method="post" onsubmit="return checkForm(this);">
    <input type="text" name="tagName" size="30" value="name goes here" />
    <input type="hidden" name="tagID" value="1" />
    <input onclick="Clicked(this);" type="submit" name="submit" value="Change" />
    <input onclick="Clicked(this);" type="submit" name="submit" value="Delete" />
 </form>
 </body>
</html>
ps
Really? why the -1?
ps
@ps: drive-by-voting; stylistic issues aside, there's nothing wrong with your answer - apart from the fact that it doesn't handle the case when the user submits the form by pressing enter in the text field in IE (IE won't use a submit button for this, but other browsers do)
Christoph
the OP asked a very specific question. "So really, I just need to know if the 'delete' button was clicked or not.Can I determine which button was clicked?" and i answered that question. :)
ps
A: 

I've been dealing with this problem myself. There's no built-in way to tell which button's submitting a form, but it's a feature which might show up in the future.

The workaround I use in production is to store the button somewhere for one event loop on click. The JavaScript could look something like this:

function grabSubmitter(input){
    input.form.submitter = input;
    setTimeout(function(){
        input.form.submitter = null;
    }, 0);
}

... and you'd set an onclick on each button:

<input type="submit" name="name" value="value" onclick="grabSubmitter(this)">

click fires before submit, so in your submit event, if there's a submitter on your form, a button was clicked.


I'm using jQuery, so I use $.fn.data() instead of expando to store the submitter. I have a tiny plugin to handle temporarily setting data on an element that looks like this:

$.fn.briefData = function(key, value){
        var $el = this;
        $el.data(key, value);
        setTimeout(function(){
            $el.removeData(key);
        }, 0);
    };

and I attach it to buttons like this:

$(':button, :submit').live('click', function () {
    var $form = $(this.form);
    if ($form.length) {
        $form.briefData('submitter', this);
    }
});
Sidnicious
A: 

Since you didn't mention using any framework, this is the cleanest way to do it with straight Javascript. With this code what you're doing is passing the button object itself into the go() function. You then have access to all of the button's properties. You don't have to do anything with setTimeout(0) or any other wacky functions.

<script type="text/javascript">
    function go(button) {
        if (button.id = 'submit1')
            //do something
        else if (button.id = 'submit2')
            //do something else
    }
</script>

<form action="update.php" method="post">
    <input type="text" name="tagName" size="30" value="name goes here" />
    <input type="hidden" name="tagID" value="1" />
    <input id="submit1" type="submit" name="submit" value="Change" onclick="go(this);"/>
    <input id="submit2" type="submit" name="submit" value="Delete" onclick="go(this);"/>
</form>
Alex Beardsley
+2  A: 

Here's an unobtrusive approach using jQuery...

$(function ()
{
    // for each form on the page...
    $("form").each(function ()
    {
        var that = $(this); // define context and reference

        /* for each of the submit-inputs - in each of the forms on
           the page - assign click and keypress event */
        $("input:submit", that).bind("click keypress", function ()
        {
            // store the id of the submit-input on it's enclosing form
            that.data("callerid", this.id);
        });
    });


    // assign submit-event to all forms on the page
    $("form").submit(function ()
    {
        /* retrieve the id of the input that was clicked, stored on
           it's enclosing form */
        var callerId = $(this).data("callerid");

        // determine appropriate action(s)
        if (callerId == "delete") // do stuff...

        if (callerId == "change") // do stuff...

        /* note: you can return false to prevent the default behavior
           of the form--that is; stop the page from submitting */ 
    });
});

Note: this code is using the id-property to reference elements, so you have to update your markup. If you want me to update the code in my answer to make use of the name-attribute to determine appropriate actions, let me know.

roosteronacid
A: 

Some browsers (at least Firefox, Opera and IE) support this:

<script type="text/javascript">
function checkForm(form, event) {
    // Firefox || Opera || IE || unsupported
    var target = event.explicitOriginalTarget || event.relatedTarget ||
        document.activeElement || {};

    alert(target.type + ' ' + target.value);
    return false;
}
</script>
<form action="update.php" method="post" onsubmit="return checkForm(this, event);">
   <input type="text" name="tagName" size="30" value="name goes here" />
   <input type="hidden" name="tagID" value="1" />
   <input type="submit" name="submit" value="Change" />
   <input type="submit" name="submit" value="Delete" />
</form>

For an inherently cross-browser solution, you'll have to add onclick handlers to the buttons themselves.

Christoph