Reputation: 4323
Okay...this is what I have:
$('#more_rows').click(function(){
var allvars = [];
var threevar = $('#third_select option:selected').text();
allvars.push(threevar);
});
This gets the text of the currently selected option for a select box. What I thought it would do is push that text into the newly created allvars
array. It pushes the text in the first time the click function happens and I get this:
["Example Text 1"]
However, when a new option is chosen from the select and the click function happens again, I get this:
["Example Text 2"]
What I want is:
["Example Text 1","Example Text 2"]
And to be able to add as many items as needed to this array.
What mistake am I making here and is there a better way to do this?
Upvotes: 0
Views: 38
Reputation: 5058
Just move the array initialization out of the function.
$(function() {
var allvars = [];
$('#more_rows').click(function(){
var threevar = $('#third_select option:selected').text();
allvars.push(threevar);
});
});
Upvotes: 2
Reputation: 26
Every Time when click event is dispatched you are creating new array.
Upvotes: 0
Reputation: 173542
Your allvars
gets redeclared each time inside the click handler; considering scoping it outside, e.g. inside the DOM ready handler:
jQuery(function($) {
var allvars = [];
$('#more_rows').click(function() {
var threevar = $('#third_select option:selected').text();
allvars.push(threevar);
});
});
Upvotes: 1
Reputation: 7256
You will need to create the array outside of the scope of the function.
Basically everytime you click on the select box, you are creating new empty variable and are pushing the value inside it.
var allvars = [];
$('#more_rows').click(function(){
var threevar = $('#third_select option:selected').text();
allvars.push(threevar);
});
Upvotes: 1