查找在<select>(没有JQuery)</select> </option>中选择了哪个<option>

时间:2013-01-15 08:34:29

标签: javascript html5 css-selectors

我有以下元素:

<select id="color" name="colorId" class="btn secondary">
    <option value="347366" selected="selected">Purple</option>
    <option value="56634">White</option>
</select>

我想找到选择的选项:

以下仅提供默认值:

document.querySelector('#color option[selected="selected"]')

(我知道如何使用JQuery,但我不能使用jQuery或任何其他类似的库)

6 个答案:

答案 0 :(得分:14)

使用:checked选择器。这适用于复选框,广播和选择

document.querySelector('#color option:checked')

表示节点

document.querySelector('#color option:checked').value

表示值

答案 1 :(得分:5)

简单的javascript:

var select = document.getElementById('color');
var currentOpt = select.options[select.selectedIndex]; 

JsBin示例:http://jsbin.com/ogunet/1/edit(打开你的js控制台)

答案 2 :(得分:1)

这将返回所选的选项值和文本。希望这适用于你..

干杯

var elt = document.getElementById('color');

 // get option selected
    var option = elt.options[elt.selectedIndex].value;
    var optionText = elt.options[elt.selectedIndex].text;

答案 3 :(得分:0)

使用getElementById()抓取<select> DOM元素并使用其参数selectedIndex

var select = document.getElementById( 'color' ),
    selIndex = select.selectedIndex;,
    selElement = select.getElementsByTagName( 'option' )[ selIndex ];

答案 4 :(得分:0)

您可以使用querySelectorAll而不是querySelector

document.querySelectorAll('option:checked')[0].innerText

document.querySelectorAll('option:checked')[0].value

答案 5 :(得分:0)

selectedOptions 是一个有效的选项,当希望从选择元素中取回选定的选项

文档中的演示:

let orderButton = document.getElementById("order");
let itemList = document.getElementById("foods");
let outputBox = document.getElementById("output");

orderButton.addEventListener("click", function() {
  let collection = itemList.selectedOptions; // <-- used here
  let output = "";

  for (let i=0; i<collection.length; i++) {
    if (output === "") {
      output = "Your order for the following items has been placed: ";
    }
    output += collection[i].label;

    if (i === (collection.length - 2) && (collection.length < 3)) {
      output +=  " and ";
    } else if (i < (collection.length - 2)) {
      output += ", ";
    } else if (i === (collection.length - 2)) {
      output += ", and ";
    }
  }

  if (output === "") {
    output = "You didn't order anything!";
  }

  outputBox.innerHTML = output;
}, false);
<label for="foods">What do you want to eat?</label><br>
<select id="foods" name="foods" size="7" multiple>
  <option value="1">Burrito</option>
  <option value="2">Cheeseburger</option>
  <option value="3">Double Bacon Burger Supreme</option>
  <option value="4">Pepperoni Pizza</option>
  <option value="5">Taco</option>
</select>
<br>
<button name="order" id="order">
  Order Now
</button>
<p id="output">
</p>