下拉菜单到值输出

时间:2017-10-31 10:06:50

标签: javascript html

道歉,这看起来非常基本。我试图在输入字段中显示下拉列表的值。我一直在戳它几个小时,不能弄清楚我做错了什么。

ON
function myFunction(){
         var e = document.getElementById("theDay");
         var dayValue = e.options[e.selectedIndex].value;
           document.getElementById("formValue").value = dayValue;
        }

2 个答案:

答案 0 :(得分:5)

您在选择中错过了 ID ,因此替换

<select name="theDay" size="7">

<select name="theDay" size="7" id="theDay">

&#13;
&#13;
function myFunction(){
        var e = document.getElementById("theDay");
        var dayValue = e.options[e.selectedIndex].value;
        document.getElementById("formValue").value = dayValue;
    }
&#13;
<form action="" name="theForm">
    <select name="theDay" size="7" id="theDay">
        <option value="0">Monday</option>
        <option value="1">Tuesday</option>
        <option value="2">Wednesday</option>
        <option value="3">Thursday</option>
        <option value="4">Friday</option>
        <option value="5">Saturday</option>
        <option value="6">Sunday</option>
    </select>
</form>
<button onclick="myFunction()">Click me</button>
to show drop down value <input type="text" id="formValue">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在您的代码中尝试此操作 theForm 是名称,但您将其称为ID。 e.options[e.selectedIndex].text获取文本和.value以获取值

function myFunction() {

  var e = document.getElementById("theDay");
  var day = e.options[e.selectedIndex].text;//value to get value
  document.getElementById("formValue").value = day

}
<form action="" name="theForm">
  <select id="theDay" size="7">
      <option value="0">Monday</option>
      <option value="1">Tuesday</option>
      <option value="2">Wednesday</option>
      <option value="3">Thursday</option>
      <option value="4">Friday</option>
      <option value="5">Saturday</option>
      <option value="6">Sunday</option>
    </select>
</form>
<button onclick="myFunction()">Click me</button> to show drop down value <input type="text" id="formValue">