8

how to store an array via jquery data method and add to that array?

1
  • 1
    Are you storing it on/with an element, or you just want a general array to use? Commented Nov 26, 2010 at 10:43

3 Answers 3

11

Since references to arrays are stored, you can do it like this:

var array = [1, 2, 3];
$.data(elem, "myArray", array);

// and later
$.data(elem, "myArray").push(4, 5, 6); 

// and later
console.log($.data(elem, "myArray"));
//-> [ 1, 2, 3, 4, 5, 6 ]
Sign up to request clarification or add additional context in comments.

Comments

6

Should be simple task:

$('#someelement').data('myarray', []);

// somewhere else
$('#someelement').data('myarray').push('foo');

// access
console.log( $('#someelement').data('myarray')[0] );

2 Comments

Why not a global variable if you're just storing it on body? :) I have my doubts that .data() or $.data() is even appropriate here...
@NickCraver: I modified it for your well-being :p
0
  var array=[1,3,5];
  var count=7;

   $('#id').data('array').push(count);

1 Comment

You should set array as the data of the element. Otherwise you'd be pushing to undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.