Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery array.push() not working

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>
like image 218
Saad Bashir Avatar asked Dec 07 '11 10:12

Saad Bashir


1 Answers

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

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

Also note that in later versions of jQuery v1.7 -> the live() method is deprecated and replaced by the on() method.

like image 89
Manse Avatar answered Oct 11 '22 18:10

Manse