猿问

如何从下拉列表中选择文本和值?

如何使用 JavaScript 从下拉列表中选择文本和值。我想使用文本我会得到选定的下拉文本。就价值而言,它运行良好。


function myFunction() {

  var x = document.getElementById("mySelect").value;

  var y = document.getElementById("mySelect").text;

  document.getElementById("demo").innerHTML = x;

  document.getElementById("demo1").innerHTML = y;

}

<div>

  <select id="mySelect">

    <option value="1">Apple</option>

    <option value="2">Orange</option>

    <option value="3">Pineapple</option>

    <option value="4">Banana</option>

  </select>



  <p>Click the button to return the value of the selected fruit.</p>


  <button type="button" onclick="myFunction()">Try it</button>


  <p id="demo"></p>

  <p id="demo1"></p>


</div>


四季花海
浏览 120回答 2
2回答

梵蒂冈之花

你可以使用:mySelect.options[mySelect.selectedIndex].text;像这样的东西:function myFunction() {&nbsp; var mySelect = document.getElementById("mySelect");&nbsp; document.getElementById("demo").innerHTML = mySelect.value;&nbsp; document.getElementById("demo1").innerHTML = mySelect.options[mySelect.selectedIndex].text;}<div>&nbsp; <select id="mySelect">&nbsp; &nbsp; <option value="1">Apple</option>&nbsp; &nbsp; <option value="2">Orange</option>&nbsp; &nbsp; <option value="3">Pineapple</option>&nbsp; &nbsp; <option value="4">Banana</option>&nbsp; </select>&nbsp; <p>Click the button to return the value of the selected fruit.</p>&nbsp; <button type="button" onclick="myFunction()">Try it</button>&nbsp; <p id="demo"></p>&nbsp; <p id="demo1"></p></div>

温温酱

var e = document.getElementById("my_Select");var value = e.value;var text = e.options[e.selectedIndex].text;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答