Get value from <option> using javascript

Does anyone know how I can get the value from all <option> using javascript?

Example:

 <select name="test" id="test"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select> 

How can I use javascript to get the whole value from <option> and output:

 1 2 3 
+4
source share
6 answers

Pie:

 var opts = document.getElementById('test').options; var vals = []; for(var i = 0, j = opts.length; i < j; i++) vals.push(opts[i].value); 
+5
source

You can use Array.prototype.map instead of an explicit loop.

 var options = document.getElementById('test').options; var values = Array.prototype.map.call(options, function(val) { return val.value; }); 

Although you need to add it to Array.prototype if you support older browsers.

There is an implementation in MDC that you can use:


 if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisp */) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") throw new TypeError(); var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t) res[i] = fun.call(thisp, t[i], i, t); } return res; }; } 
+2
source
 var options = document.getElementById('test').options; 

See https://developer.mozilla.org/en/DOM/HTMLOptionsCollection

Edit: For completeness

 var options = document.getElementById('test').options; var values = []; for (var i = 0; i < options.length; i++) { var option = options.item(i); var value = option.value || option.text; // For IE values.push(value); } 

From memory, some versions of Internet Explorer do not return the text content of the option for the value property unless the value attribute is set.

0
source

you can do it with javascript like this

  var opt = document.getElementById ('idOfYourSelect'). options;

 for (var i = 0, ii = opt.length; i <ii; i ++) {
     console.log (opt [i] .value);
 }

if you use jQuery, it could be like

  var opt = $ ('# idOfYourSelect options');

 for (var i = 0, ii = opt.length; i <ii; i ++) {
     console.log (opt [i] .value);
 }
0
source

i recomment use the jQuery library for this and use the .each () method to query all the "tags" tags in the "select" section.

0
source

I need all the values ​​and its labels, so I used the code below

 var opts = document.getElementById('state_of_birth').options; var vals = []; var txt = []; for(i=0,j=opts.length;i<j;i++) { vals.push(opts[i].value); txt.push(opts[i].text); } var k=i; for(i=0;i<k;i++) { window.alert(vals[i]); window.alert(txt[i]); } 
0
source

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


All Articles