Jquery collects all parameter values ​​from a select box in a JSON array

I have a selection box.

<select id='x'> <option value='1'>'Vineet'</option> <option value='2'>'Vivek'</option> <option value='3'>'Madhu'</option> </select> 

Parameters are added dynamically to it. In the end, I want to collect the values ​​of ALL elements contained in this selection field into an array. I was looking for a forum for an answer, but Q / A is for getting the "selected" option.

I tried this:

 var myList = []; $('#x').each(function() { myList.push( $(this).value() ) }); 

In firebug, it gives this error:

missing} after the property list

But I do not see the missing } . What am I doing wrong here?

+6
source share
2 answers

You need to scroll through each option element inside select, and not just select itself, also the correct method to get the input value in jQuery val() , try the following:

 myList = []; $('#x option').each(function() { myList.push($(this).val()) }); 

Script example

You can also use map() :

 var myList = $('#x option').map(function() { return this.value; }).get(); 

In both cases, the variable myList will contain an array of strings.

+10
source

Try using the jQuery function to get the value of the element (wrapped in a jQuery object) .val() rather than .value() - this can cause some confusion, although I cannot be sure.

As a side note, your selector is incorrect for what you want. $('#x') will return all elements having id of x - which should be only ever one element - then .each() will .each() over this set of elements (so that it will call the function once). You simply get an array containing one value, which will be the currently selected input value <select> .

Instead, use $('#x > option') , which will return all <option> elements that are immediate children of the <select> element with id of x .

+1
source

Source: https://habr.com/ru/post/908322/


All Articles