So..i'm having this problem for couple of days not knowing how to do this,and i need help.
I have multiple buttons and clicking all of them is redirecting me to same function and from that function is going to another function specified for that button. Any idea how can i go true couple of functions knowing which button is clicked? example :
<html>
<button type="button" onclick="myFunction()" id="1">Button1</button>
<button type="button" onclick="myFunction()" id="2">Button1</button>
<button type="button" onclick="myFunction()" id="3">Button1</button>
<script>
function myFunction()
{
var x=0;
if (button 1){
x=1;
myFunction1(x);}
if (button 2){
x=2;
myFunction2(x);}
if (button 3){
x=3;
myFunction3(x);}
...
myFunction3(x){
alert(x);
}
}
</script>
</html>
Easiest way would probably be to pass in the element into the function:
No need to think about event arguments or anything like that.
IF you can change the HTML, try:
And change your JS to:
It's a bit nicer in a switch:
At its simplest:
JS Fiddle demo.
Though I'd amend the above to use unobtrusive JavaScript, moving the JavaScript event-handling from the elements' HTML mark-up:
JS Fiddle demo.
Or, to make it even easier (and add the event-handling to one element, rather than three):
JS Fiddle demo.
Incidentally, while it's valid (under HTML 5, not under HTML 4) to have an
id
that starts with a numeric character (0-9), in CSS it's difficult to target those elements (leading numeric characters require escaping, in any one of various ways); so it's still advisable to have a predictable alphabetic prefix to thoseid
s.References:
element.addEventListener()
.for () {...}
loop.`switch () {...}
statement.you could put