Page 1 of 1

Javascript validation based on submit button pressed

Posted: Wed Dec 28, 2005 1:53 pm
by alvinphp
If a form has two submit buttons and you submit the form how can you tell which button was pressed in javascript? My validation rules are different depending on which button is pressed and I am using OnSubmit in the form tag to call the javascript.

The way I do it now is call the javascript from the button and submit the form in the javascript. I wanted to try something different and see if I can tell which button is being pressed when I do an onsubmit from the form tag.

TIA

Posted: Wed Dec 28, 2005 2:48 pm
by josh
the onClick event on the submit button itself should work,

then you need

Code: Select all

document.forms['yourform'].submit()
to be called in your validation routine to actually submit the form

Posted: Wed Dec 28, 2005 3:10 pm
by alvinphp
I know how to do that. I want to know if there is a way in javascript to know which button was pressed in a form that has multiple buttons.

*edit*

hmm, this might not be possible. seems like such a simple thing.

Posted: Wed Dec 28, 2005 11:42 pm
by n00b Saibot
you can check for the name attribute of the event.srcElement :arrow:

Code: Select all

<script>
function onBtnClick()
{
 btnName = event.srcElement.name;
 alert("You pressed "+btnName+" Button!");
}
</script>
<form>
<input type="button" name="Simple" value="Simple Button" onclick="onBtnClick()" />
<input type="submit" name="Submit" value="Submit Button" onclick="onBtnClick()" />
<input type="reset" name="Reset" value="Reset Button" onclick="onBtnClick()" />
</form>
:wink: