简体   繁体   中英

Get the value of a non-selected option in a dropdown list

The following Javascript code gets the list of all options in a dropdown list. Eg)

first option
second option
third option

var dropDown = document.getElementById('dropDownId'); var optionsList= dropDown.options;

The is also a value attribute, id , associated with each drop down option. How can I get the id of an option? Eg., How would I get the id of second option ?

只是

var idOfSecondOption = document.getElementById('dropDownId').options[1].id

Say you have

<select id="dropDownId">
    <option id="A" value="X">first option</option>
    <option id="B" value="Y">second option</option>
    <option id="C" value="Z">third option</option>
</select>

Then you could do something like

function getIdsOfOptions(select) {
    return Array.prototype.map.call(select.options, function (e) {return e.id;});
}
var option_ids = getIdsOfOptions(document.getElementById('dropDownId'));
// ["A", "B", "C"]
console.log(option_ids[1]); // log id of second <option>
// B logged

DEMO (code is run after Elements exist)

You javascript:

var dropDown = document.getElementById('dropDownId');
var optionsList= dropDown.options;

returns an array of the dropdown options. So as long as you know what order they are in, you can grab any of the by their index in the array. eg So give then list:

<select id="dropDownId" name="cars">
  <option value="volvo">Volvo XC90</option>
  <option value="saab">Saab 95</option>
  <option value="mercedes">Mercedes SLK</option>
  <option value="audi">Audi TT</option>
</select>

this line console.log(optionsList[0]); will return

<option value="volvo">Volvo XC90</option>

and once you have that, you could really get any property you needed from that item, like an id.

Here's a fiddle: http://jsfiddle.net/jxwb4oj6/

<!doctype html>
<html>
  <body>
    <select id="list-1">
      <option id="opt-id-1" name="opt-1" value="val-1">Option 1</option>
      <option id="opt-id-2" name="opt-2" value="val-2">Option 2</option>
      <option id="opt-id-3" name="opt-3" value="val-3">Option 3</option>
    </select>
  </body>

  <script>
    // first option (faster execution)
    var list = document.getElementById('list-1');
    var options = list.options;
    console.log(options[0].id);
    console.log(options[1].id);
    console.log(options[2].id);

    console.log('---');

    // another option (slower execution)
    console.log(document.querySelectorAll('#list-1 option')[2].id);
    console.log(document.querySelectorAll('#list-1 option')[1].id);
    console.log(document.querySelectorAll('#list-1 option')[0].id);
  </script>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM