+ 1

Event handling in JavaScript using functions with arguments. Is it possible?

I got one problem building my website: I have two buttons, "right" and "left", and I want to call the function turn() using the onClick event handler. The function turn() has one argument: dir, which is either "right" or "left", depending on which button was pressed. I call the function like this: <a href="#" onclick="turn("left")"> <--! I use links as buttons as you see --> For some reason this solution doesn't work for me. I tried it othervise before: I used two different functions, right() and left() for the two possible input "right" and "left". These functions has NO arguments, and the code works perfectly with them... It is possible, that I made a mistake somwhere else in the code, but I need an answer for this problem before I keep searching for bugs. Thanks in advance for the answers!

26th Aug 2017, 12:37 PM
Levente Varga
Levente Varga - avatar
4 odpowiedzi
+ 8
<a href=# onclick=turn("left")> / <a href="#" onclick="turn('left')"> / <a href="#" onclick="turn(\"left\")"> / <a href="#" onclick="turn(&#34;left&#34;)"> / <a href="#" onclick='turn(&#39;left&#39;)'> More: at n.2 will be auto-converted to n.3 by browser
26th Aug 2017, 12:41 PM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 5
..... bro 'turn("left")' not 'turn('left')' and "turn('left')" not "turn("left")" It is cus of unmatch string But \" I'm not sure why It's not work right now :/ In past it work
26th Aug 2017, 1:13 PM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 4
Else, use numeric codes ;D <a onclick="turn(0);"> <a onclick="turn(1);"> ... or even in a two states cases, use boolean: <a onclick="turn(false);"> <a onclick="turn(true);"> That can be easily converted (or simply tested) to string value in your called function: function(arg) { var str; if (arg==1) str = 'left'; else str = 'right'; } ... or a few shortly (in two states cases): function(arg) { var str = (arg==1) ? 'left' : 'right'; } ... or even more shortly if boolean used (or 0 and 1, which are equivalent to 'false' and 'true'): function(arg) { var str = (arg) ? 'left' : 'right'; } ... and in this last case you can also shorten a few the html code: <a onclick="turn();"> <a onclick="turn(1);"> ... as 'undefined' is also equivalent to 'false' ;)
26th Aug 2017, 3:47 PM
visph
visph - avatar
+ 1
Thank you for the answer, however, the following solutions don't work for me: <a href="#" onclick="turn("left")"> <a href="#" onclick='turn('left')'> <a href="#" onclick="turn(\"left\")"> The two others are perfect, thank you!
26th Aug 2017, 1:04 PM
Levente Varga
Levente Varga - avatar