Detecting which submit button triggered form submission

I have multiple submit buttons in a form, with the same name. ie:

<input type='submit' name='doaction' value='walk'>
<input type='submit' name='doaction' value='run'>

Is it possible to detect which submit button was presed, from within the onsubmit handler for the form, or would I need to apply onclick handlers for each button, and submit the form as part of the function?

Hey, here’s a crazy idea. Keep the standard onsubmit event, and have the onclick event update a property within the form.

This works due to the onclick event always being processed before the onsubmit event.


function onclickHandler() {
    this.form.submitValue = this.value;
}

function onsubmitHandler () {
    var submitValue = this.submitValue;
    ...
    return false;
}

var form = document.getElementById('actions');
form.elements.doaction[0].onclick = onclickHandler;
form.elements.doaction[1].onclick = onclickHandler;
form.onsubmit = onsubmitHandler;

Yeah, that’s what I ended up doing. I couldn’t figure out how to detect the clicked element (button), rather than the element which triggered the event (form) either!

Hmmm. In your example the target/srcElement is still the form element, even when the button is clicked.

Here it is tidied up a bit.



(function () {
    function submitClickHandler() {
        this.form.submitValue = this.value;
    }

    function onsubmitHandler() {
        var submitValue = this.submitValue;
        // process submit button value here ...
        return false;
    }

    var form = document.getElementById('actions');
        els = form.getElementsByTagName('input'),
        i;
    for (i = 0; i < els.length; i += 1) {
        el = els[i];
        if (el.type === 'submit') {
            el.onclick = submitClickHandler;
        }
    }

    form.onsubmit = onsubmitHandler;
}());

Ahh curses, I’m forgetting something about how to retrieve the clicked-on element, rather than the element that triggered the event. Does that not apply to onsubmit events? Perhaps so.

Here’s an alternative, where you individually assign an onclick handler to the submit buttons.



var onclickHandler = function () {
    var el = this;
    switch (el.value) {
    case 'walk':
        walk();
        break;
    case 'run':
        run();
        break;
    default:
        doNothing();
        break;
    }
    return false;
};
function walk() {
    alert('walk');
}
function run() {
    alert('run');
}

var form = document.getElementById('actions');
form.elements.doaction[0].onclick = onclickHandler;
form.elements.doaction[1].onclick = onclickHandler;