如何将onclik文本移动到文本区域?

时间:2019-11-19 11:07:56

标签: javascript html

当我单击苹果时如何

Apple的文本区域,而不是数字。

function getIndex() {
  document.getElementById("demo").innerHTML =
    document.getElementById("mySelect").selectedIndex;
}
<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>
<input type="button" onclick="getIndex()" value="Display the index of the selected option">
<p id="demo"></p>

我编译选择选项中的值,我希望文本显示出来而不是数字

2 个答案:

答案 0 :(得分:1)

使用option[index].text

获取选定的索引并获取相应选项的值

<head>
  <script>
    function getIndex() {

      var index = document.getElementById("mySelect").selectedIndex;
      document.getElementById("demo").innerHTML =
        document.getElementById("mySelect").options[index].text;
    }
  </script>
</head>

<body>
  <select id="mySelect">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
  </select>
  <input type="button" onclick="getIndex()" value="Display the index of the selected option">
  <p id="demo"></p>

答案 1 :(得分:1)

将此行document.getElementById("mySelect").selectedIndex;替换为document.getElementById("mySelect").value;