Rourke McLaren
Rourke McLaren

Reputation: 69

Pushing content to array

I'm trying to add content from a div to an array. Basically if you click the divs for Apple, Banana and Kiwi, the resulting array will store 'Apple, Banana, Kiwi' in the order they were clicked.

$('.fruit').click(function addFruit() {
  var fruits = [];
  var fruit = $(this).text();
  fruits.push(fruit);
  $('.result').text(fruits + ', ');
});

Here's my fiddle: https://jsfiddle.net/bjhj5p41/2/

Any ideas?

Upvotes: 3

Views: 74

Answers (1)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

var fruits = [];  // make it global
$('.fruit').click(function() { // no need to use addFruit here
  var fruit = $(this).text();
  fruits.push(fruit);
  $('.result').text(fruits); // use (fruits) cause its an array it will return commas itself
});

Working Demo

ِAdditional: I think no need to push the same value twice in array so you can use

if($.inArray(fruit,fruits) == -1){
   // value not in array
}

Demo

Upvotes: 6

Related Questions