turkeyhundt
turkeyhundt

Reputation: 214

Accessing javascript array from onclick function

I am using jQuery and populating an array on document.ready.

In my page I have some elements with a click event. I defined that function outside of the document.ready function.

I can't seem to figure out how to access that array variable from within my onclick function.

To simplify, I would like something like this to work:

$(document).ready(function(){
  var artists = new Array();
  artists.push('item1');
  artists.push('item2');
});

function clickLink() {
  alert(artists[0]);
}

Upvotes: 1

Views: 1251

Answers (4)

Muhammad
Muhammad

Reputation: 7324

A simple solution is to remove the var keyword when you declare the array variable, which will make the variable global and that is not recommended and another solution would be to declare your array outside the function so that it can be referenced from onclick function.

Upvotes: 0

kind user
kind user

Reputation: 41893

You have to declare the artists array outside the document.ready() function and bind the function with the click event.

var artists = new Array();

$(document).ready(function() {
  artists.push('item1');
  artists.push('item2');
});

$('button').click(function() {
  console.log(artists[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click</button>

Upvotes: 1

Bulent Vural
Bulent Vural

Reputation: 2688

Many ways, one of the easiest, move your click hander inside the .ready() function. And you need to bind it to the element there instead of inline attribute:

$(document).ready(function(){
  var artists = new Array();
  artists.push('item1');
  artists.push('item2');

  $('#idOfTheElement').click(function() {
    alert(artists[0]);
  });
});

Upvotes: 3

&#193;lvaro Touz&#243;n
&#193;lvaro Touz&#243;n

Reputation: 1230

hi you lost scope of creation of array, so there is two ways to solve it

Put all in same scope:

    $(document).ready(function(){
      var artists = new Array();
      artists.push('item1');
      artists.push('item2');
    function clickLink() {
      alert(artists[0]);
    }
    });

Declare array as global:

var artists = new Array();
$(document).ready(function(){

      artists.push('item1');
      artists.push('item2');

    });
function clickLink() {
      alert(artists[0]);
    }

Upvotes: 2

Related Questions