Link to home
Start Free TrialLog in
Avatar of nvs_victor
nvs_victorFlag for United States of America

asked on

Which button was pressed in a form with Javascript?

Hi experts!

I’ve been struggling with this issue for a while.

So I have a form like this:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validation

But the difference is that I have multiple buttons in my form… I will need to find out which button was pressed. How do I do this?

For example, below code has two buttons instead of one:  

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input name = "1" id="1" type="submit" value="Submit">
<input name = "2" id="2" type="submit" value="Submit">
</form>
</body>

</html> 

Open in new window


So how do I know which button was pressed? I need to find out so that I can do validations with Javascript for multiple buttons.

Thanks so much!
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nvs_victor

ASKER

Hey GaryC123!

That does it :)  

Thanks a lot!
Thank you soooooooooooooooooooooooooo much! This little issue was driving me insane... I probably was missing one simple thing, and went looking for other complex solutions.