Is it possible to pass an array from onClick to javascript function?
Solution 1
Yes, it's possible. You'd probably want to use array initializer syntax (aka an "array literal"), and you need to mind your quotes:
<input type="button" value="myButton" onClick="return myFunction(['string1','string2'])">
If your attribute value is quoted with double quotes, you can't use a literal double quote within the value. The easiest thing is to use single quotes, although since the text of attribute values is HTML text (something people tend to forget), you could use "
if you liked. (I wouldn't. :-) ) And the fact that the text is HTML is something to keep in mind for the contents of the array...
It may well not be desirable, though. You might consider using modern event handling techniques to hook up the handler, for instance:
document.querySelector("input[type=button][value=myButton]").addEventListener("click", function() {
myFunction(['string1','string2'])
}, false);
If you need to support old IE, use a DOM library like jQuery, or something like the hookEvent
function in this other answer to handle the fact that IE8 and earlier don't have addEventListener
.
Solution 2
You have 2 problems. array
should be Array
, as JS is case-sensitive. You could also use the short form [1,2,3]
. Then notice that your onclick
attribute is wrapped with double quotes. You need to escape the quotes inside your JS by doing \"
or by simply using '
:
function myFunction(arr){
// for demo purposes
alert( JSON.stringify(arr) );
}
<input type="button" value="myButton" onClick="return myFunction(['string1','string2'])">
I would also suggest avoiding inline JS as T.J. Crowder mentioned it.
Torbjörn Loke Nornwen
Updated on March 11, 2020Comments
-
Torbjörn Loke Nornwen about 4 years
In PHP I can write a function like this:
function myFunction(myArray) { foreach(myArray) { // do stuff with array } }
Then I can call it like this (maybe ugly, but still works):
myFunction(array("string1","string2"));
I want to do something similar with JavaScript but can't figure out if it's possible to pass arrays to functions like that. This is my psuedo-function:
function myFunction(myArray) { for (index = 0; index < myArray.length; ++index) { // do stuff with array } }
I want to call it from a button using onClick like this:
<input type="button" value="myButton" onClick="return myFunction(array("string1","string2"))">
Can this be accomplished in a simle way?