Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning select list values to array

I have an array initialised in script

var listarray = new Array(); 

And have a dynamically created select list ---

<select multiple size=6 width=150 style="width:150px" name="ToLB" >
</select>

My question is how to assign all values of select list to the array. Thanks in advance.

like image 963
NewBee Avatar asked Apr 23 '13 07:04

NewBee


3 Answers

You can do this like :

JQuery-

var optionVal = new Array();
    $('select option').each(function() {
            optionVal.push($(this).val());
        });

Javascript-

var x = document.getElementById("mySelect"); 
var optionVal = new Array();
for (i = 0; i < x.length; i++) { 
    optionVal.push(x.options[i].text);
}

This stores all the options in your select box in the array optionVal.

Hope it helps you.

like image 159
qwerty Avatar answered Oct 21 '22 03:10

qwerty


You can use getElementsByTagName to get all the selectbox as object.

var el = document.getElementsByTagName('select')

And in jQuery you can do it as below.

var arrayOfValues = $("select").map(function() { return this.value; });
like image 38
Dipesh Parmar Avatar answered Oct 21 '22 03:10

Dipesh Parmar


Using plain javascript this is something that would work for you. Now, I've assumed that you have at least some options in your select

html

<select id="selecty" multiple size=6 width=150 style="width:150px" name="ToLB" >
    <option value="monkey">Monkey</option>
</select>

javascript

var listarray = new Array();
//NOTE: Here you used new as a variable name. New is a reserved keyword so you cant use that as a variable name.

var select = document.getElementById('selecty'); // get the select list

for(var i = 0; i < select.options.length; i++){
   listarray.push(select.options[i].value);
}
console.log(listarray);
>> ["monkey"]

Fiddle here:

http://jsfiddle.net/mQH7P/

like image 3
Henrik Andersson Avatar answered Oct 21 '22 05:10

Henrik Andersson