Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 901
Rourke McLaren Avatar asked Feb 27 '26 21:02

Rourke McLaren


1 Answers

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

like image 160
Mohamed-Yousef Avatar answered Mar 02 '26 09:03

Mohamed-Yousef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!