Reputation: 3
So I have this code below. Whenever I click the button, it goes to the render_initialize_board and console.logs only the first element of the array fixed. How to pass the whole array to the function using onclick in javascript?
function render_initialize_board(N,fixed){
console.log(fixed);
}
N = 4;
var fixed = [0,1,0,0]
$("#header ul").append('<li><a href="#'+N+'" data-toggle="tab" onclick="render_initial_board('+N+','+fixed+')">'+ N +'</a></li>');
Upvotes: 0
Views: 1336
Reputation: 1168
By concatenating those strings and variables, the fixed
array is being converted to a string.
Because of that, the function call looks like this when the click event is handled: render_initialize_board(4, 0, 1, 0, 0)
In that case, the fixed
parameter does, in fact, equal 0.
To make it easier to read while avoiding the issue, just use jQuery's click
method.
function render_initialize_board(N, fixed) {
console.log(fixed);
}
var N = 4;
var fixed = [0, 1, 0, 0];
$("#header ul")
.append('<li><a href="#' + N + '" data-toggle="tab">' + N + "</a></li>")
.click(() => render_initialize_board(N, fixed)); // Replace "onclick" with this
Upvotes: 0
Reputation: 92440
You have a few too many quotes. With those quotes you are passing a string representation of the array to your function, which from its point of view looks like separate arguments for each element. You can just use:
onclick="render_initialize_board(N, fixed)"
function render_initialize_board(N, fixed, fixed2) {
console.log(fixed);
}
N = 4;
var fixed = [9, 1, 0, 0]
$("#header ul").append('<li><a href="#' + N + '" data-toggle="tab" onclick="render_initialize_board(N, fixed)">' + N + '</a></li>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header">
<ul>
</ul>
</div>
Upvotes: 1