Reputation: 1
I'm having trouble passing an array as an argument of a function:
function test() {
var array1 = ["1","2"];
var show = "<p>Show: <a href=# onClick='showArray("+array1+")'>Click to show array</a></p>";
}
So I need to have an onClick as it is there, but when I pass an array and call the function
function showArray(array) { alert (array.length); }
Returns nothing. Why not work?
EDIT:
function test() {
var array1 = [];
array1[0] = {
"type" : 0,
"message" : "example",
"from" : "path1",
"count" : 1,
"isChecked": false
};
array1[1] = {
"type" : 2,
"message" : "example",
"from" : "path2",
"count" : 50,
"isChecked": false
};
var show = "<p>Show: <a href=# onClick='showArray(["+array1+"])'>Click to show array</a></p>";
}
Upvotes: 0
Views: 94
Reputation: 2459
Everyone is missing it:
var show = "<p>Show: <a href='javascript:showArray(array1)'>Click to show array</a></p>"
href="javascript:"
instead of onclick
Upvotes: 1
Reputation: 31121
Your onclick calls showArray
but your function is called show
.
If you inspect the DOM, you'll see what the JS is creating:
<a href="#" onclick="showArray(1,2)">Click to show array</a>
That's not valid! So just change it to
<a href='#' onClick='showArray(array1)'>
and the DOM will be exactly that, as well. This is valid.
Upvotes: 0
Reputation: 1857
try this:
<script>
var array1 = ["1","2"];
function showArray(myArray) { alert (myArray.length); }
</script>
<p>Show: <a href='#' onClick='showArray(array1); return false;'>Click to show array</a></p>
and here is a link to this example: http://jsfiddle.net/eNXx5/
Upvotes: 0
Reputation: 11342
Your code is not working because the evaluated value of the show
var is the following:
"<p>Show: <a href=# onClick='showArray(\"1\",\"2\")'>Click to show array</a></p>"
Which means that the showArray
function is receiving two parameters ("1" and "2") and neither of them is an array, but a string.
To make your code work, use this:
var show = "<p>Show: <a href=# onClick='showArray(["+array1+"])'>Click to show array</a></p>"
By this way, the evaluated value will be:
"<p>Show: <a href=# onClick='showArray([\"1\",\"2\"])'>Click to show array</a></p>"
Which means that showArray
will receive only one parameter: the ["1","2"] array
Upvotes: 2
Reputation: 7984
Take out the quotes:
var show = "<p>Show: <a href=# onClick='showArray(array1)'>Click to show array</a></p>";
Upvotes: 0