javascriptweb-applications

Identify the value of clicked submit button with multiple submit buttons


I have situation where i need to track which submit button click in order to do set variables according to that. Below is the test code,

<script>
function submitForm(form) {
    alert(document.getElementById('sb').value);
    if (document.getElementById('sb').value=="One") {
        //Do something
    }
    return true;
}
</script>


<form action="" method="get" onsubmit="return submitForm(this);">
    <input type="submit" name="sb" value="One">
    <input type="submit" name="sb" value="Two">
    <input type="submit" name="sb" value="Three">
</form>

The alert always shows One even if i click button Two or Three. But the url change with clickable parameter. How to alert the value which is in the clickable submit button?

Note: I want a solution with out JQuery

EDIT: I change the code bit which the onsubmit call the submitForm(this); The problem is even use document.forms[0].sb.value its undefined because document.forms[0].sb return a node list of all submit buttons as its same as with document.getElementById('sb')


Solution

  • Continuing the answer above:

    <script>
    function m(value) {
    alert(value);
    }
    </script>
    
    <input type="button" value="One" onClick="m(this.value)">
    <input type="button" value="Two" onClick="m(this.value)">
    <input type="button" value="Three" onClick="m(this.value)">
    

    You can of course see what's the id:

    <input type="button" id='myId' value="Three" onClick="m(this.id)">