Reputation: 4519
I have been trying to add variables from a dropdown into an array using Jquery array.push() function but for some odd reason it is not working. Following is the jsFiddle link: http://jsfiddle.net/dKWnb/3/
JavaScript :
$("#test").live("click",function() {
var myarray = new Array();
myarray.push($("#drop").val());
alert(myarray);
});
HTML
<Select name=drop id=drop>
<option value=1>1</option>
<option value=2>2</option>
</select>
<input type=button name=test id=test value=test>
Upvotes: 19
Views: 173134
Reputation: 1
var array = [];
var element = "anything you want in the array";
array.push(element); // array = [ "anything you want in the array" ]
Upvotes: -1
Reputation: 3623
another workaround:
var myarray = [];
$("#test").click(function() {
myarray[index]=$("#drop").val();
alert(myarray);
});
i wanted to add all checked checkbox to array. so example, if .each is used:
var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
if (this.checked) {
var p=$('.pp').eq(idx).val();
vpp[incr]=(p);
incr++;
}
});
//do what ever with vpp array;
Upvotes: 4
Reputation: 38137
Your HTML should include quotes for attributes : http://jsfiddle.net/dKWnb/4/
Not required when using a HTML5 doctype - thanks @bazmegakapa
You create the array each time and add a value to it ... its working as expected ?
Moving the array outside of the live() function works fine :
var myarray = []; // more efficient than new Array()
$("#test").live("click",function() {
myarray.push($("#drop").val());
alert(myarray);
});
Also note that in later versions of jQuery v1.7 -> the live() method is deprecated and replaced by the on() method.
Upvotes: 33
Reputation: 17454
Your code alerts the current value of the dropdown for me, showing that it has properly pushed into the array.
Are you wanting to keep old values and append? You're recreating the array each time, meaning that the old value gets clobbered.
Here's some updated code:
var myarray = [];
$("#test").click(function() {
myarray.push($("#drop").val());
alert(myarray);
});
Upvotes: 7