开发者

get value from <option> with javascript [duplicate]

This question already has answers here: Check if dropdown's selected option is not the first with JavaScript (3 answers) Closed 8 years ago.

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

example:

<select name="test" id="test">
  <option value="1">one</option>
  <optio开发者_开发技巧n value="2">two</option>
  <option value="3">three</option>
</select>

How can I using javascript to retrieved all the value from <option> and output:

1
2
3


Pie:

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


You can use Array.prototype.map instead of explicitly looping.

var options = document.getElementById('test').options;

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

Though you'll need to add it to Array.prototype if you're supporting older browsers.

There's an implementation at MDC you can use:

  • https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map

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


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 using jQuery it can be like this

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

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


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 option's text content for the value property if no value attribute is set.


i recomment use for this an jQuery library & use .each() method for query an all "options" tags under defined "select".


I wanted all values and its labels so i used below code

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜