Joseph Met
Joseph Met

Reputation: 1

Javascript argument in function

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

Answers (5)

Nadav S.
Nadav S.

Reputation: 2459

Everyone is missing it:

var show = "<p>Show: <a href='javascript:showArray(array1)'>Click to show array</a></p>"
  1. You have to take out the quotes if you use a variable.
  2. The "href" attribute didn't contain quotes.
  3. It is recommended to use href="javascript:" instead of onclick

Upvotes: 1

sachleen
sachleen

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.

DEMO

Upvotes: 0

mohamed elbou
mohamed elbou

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

Danilo Valente
Danilo Valente

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

Lee Taylor
Lee Taylor

Reputation: 7984

Take out the quotes:

var show = "<p>Show: <a href=# onClick='showArray(array1)'>Click to show array</a></p>";

Upvotes: 0

Related Questions