Javascript validation based on submit button pressed

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
alvinphp
Forum Contributor
Posts: 380
Joined: Wed Sep 21, 2005 11:47 am

Javascript validation based on submit button pressed

Post 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
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post 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
alvinphp
Forum Contributor
Posts: 380
Joined: Wed Sep 21, 2005 11:47 am

Post 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.
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post 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:
Post Reply