khng wrote:
When there is a HTML Form with lots of input elements, how can I know
which element is triggering the form submit action with the help of
javascript.
Let's restore the intended message first ;-)
"I have a HTML form with several SUBMIT buttons in it. When user
submits the form I need to detect which one of submit buttons has been
used. Please help me. Thank you in advance."
You are welcome. This question is not a trivia at all, because onsubmit
the only visible source of event is the form itself. I guess the
possibility to have several submit buttons with different values was
not noticed while designing the form event model.
Good news is that "click" event fires before "submit" event. Bad news
is that you need to loop through all INPUT's to get the right ones and
attach onclick handlers to them. All together it comes to something
like:
<html>
<head>
<title>Detect submit button</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">
var submitter = null;
function validate(f) {
alert(submitter.value);
return false;
}
function getSubmitter(e) {
if ((e)&&(e.target)) {
submitter = e.target;
}
else if ((event)&&(event.srcElement)) {
submitter = event.srcElement;
}
else {
/*NOP*/
}
}
function init() {
var ins = document.forms[0]
.getElementsByTagName('INPUT');
for (var i=0; i<ins.length; i++) {
if (ins[i].type.toLowerCase() == 'submit') {
ins[i].onclick = getSubmitter;
}
}
}
window.onload = init;
</script>
</head>
<body>
<form method="get" action="" onsubmit="return validate(this)">
<input type="submit" name="Submit1" value="Submit1">
<input type="submit" name="Submit2" value="Submit2">
</form>
</body>
</html>