从选择选项

时间:2018-05-23 12:33:10

标签: javascript html css

我想要更改用户写下单词的输入字段。然后使用document.getElementById("myInput1").value;

将该单词带入javascript

所以基本上,在HTML中就是这样:

<input type="text" id="myInput1" placeholder="" style="z-index:1"></input>
<span onclick="newElement1()" class="addBtn" style="border-radius: 0px; height:30px">Add</span>

但是知道我想要的是一个选择字段,因此用户将无法输入错误或列表中不存在的内容:

  <select>
    <option value="0">Select car:</option>
    <option value="1">Audi</option>
    <option value="2">BMW</option>
    <option value="3">Citroen</option>
    <option value="4">Ford</option>
    <option value="5">Honda</option>
    <option value="6">Jaguar</option>
    <option value="7">Land Rover</option>
    <option value="8">Mercedes</option>
    <option value="9">Mini</option>
    <option value="10">Nissan</option>
    <option value="11">Toyota</option>
    <option value="12">Volvo</option>
  </select>

所以在不改变很多东西的情况下,我想通过选择字段在html中替换输入文本。那么用户将选择什么,它将具有id“myInput1”(当然javascript知道如何处理这个)。

2 个答案:

答案 0 :(得分:1)

您只需要询问value select而不是input字段。

顺便设置border-radius:0与完全不设置相同,您无法在height上设置span(除非您更改{{1} } spandisplay:block)因为display:inline-block元素是内联元素,而span由其内容决定。

&#13;
&#13;
height
&#13;
// If an element has an id, then .getElementById() is the most direct way
// to access it.
let make = document.getElementById("carMake");

// If an element doesn't have an id, .querySelector() is very easy to use
// to get a reference to the element. Here, the selector is for the .addBtn class
document.querySelector(".addBtn").addEventListener("click", function(){
  // Get the text of the selected <option>
  console.log("You selected: ", carMake.options[carMake.selectedIndex].textContent);
  
  // Get the value of the selected <option>
  console.log("You selection has a value of: ", carMake.value);  
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

    <span class="addBtn" onclick="newElement1()">Add</span>

          <select id="carMake">
            <option value="0">Select car:</option>
            <option value="1">Audi</option>
            <option value="2">BMW</option>
            <option value="3">Citroen</option>
            <option value="4">Ford</option>
            <option value="5">Honda</option>
            <option value="6">Jaguar</option>
            <option value="7">Land Rover</option>
            <option value="8">Mercedes</option>
            <option value="9">Mini</option>
            <option value="10">Nissan</option>
            <option value="11">Toyota</option>
            <option value="12">Volvo</option>
          </select>
 <script>
       function newElement1() {
        var e= document.getElementById("carMake");
        var value = e.options[e.selectedIndex].value;
        $('#myInput1').val(value);  }
</script>