JQuery array.push () not working

I am trying to add variables from a drop-down list to an array using the jQuery function array.push (), but for some odd reason, it does not work. Below 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> 
+9
source share
3 answers

Your HTML should include quotes for the attributes: http://jsfiddle.net/dKWnb/4/

Not required when using an HTML5 document - thanks @bazmegakapa

You create an array every time and add a value to it ... does it work as expected?

Moving an 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); }); 

http://jsfiddle.net/dKWnb/5/

Also note that in later versions of jQuery v1.7 β†’ the live () method is deprecated and replaced with the on () method.

+14
source

Your code warns the current value of the dropdown for me, showing that it is correctly placed in the array.

Do you want to keep old values ​​and add? You recreate the array each time, which means the old value gets clobbered.

Here is the updated code:

 var myarray = []; $("#test").click(function() { myarray.push($("#drop").val()); alert(myarray); }); 

jsFiddle

+4
source

another workaround:

 var myarray = []; $("#test").click(function() { myarray[index]=$("#drop").val(); alert(myarray); }); 

I wanted to add all the checked checkbox to the array. so an 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; 
0
source

All Articles