簡體   English   中英

將所選下拉菜單項中的文本應用於輸入字段(html,javascript)

[英]Apply text from selected dropdownmenu item to input field (html,javascript)

當我從下拉菜單ID中選擇一個要在輸入字段中查看的項目時,如果選擇了另一個項目,我想將此項目添加到由逗號分隔的輸入字段中。

目前,這是html:

<div>
   <input type="text" id="box" placeholder="Using..." style="width: 400px">
   <select style="width: 180px" id="drop">
      <option value="" disabled selected>Select</option>
      {% for stuff in stuffs%}
      <option value="{{stuff}}" onclick="ApplyField(drop,box)">{{stuff}}</option>
      {% endfor %}                  
   </select>
</div>

和javascript:

<script>
   function ApplyField(drop_id,box_id)
   {
     var e = document.getElementById(field_id);
     var selectedItem = e.options[e.selectedIndex].text;
     if (document.getElementById(box_id).text == "")
       document.getElementById(box_id).text = selectedItem;
     else 
       document.getElementById(box_id).text = document.getElementById(box_id).text + "," + selectedItem;
   }    
</script>

但是以某種方式我的腳本不會將輸入框項設置為selecteditem,盡管代碼對我而言似乎是合乎邏輯的。 這是我第一次編寫javascript,因此很可能錯過了一些瑣碎的事情。 任何幫助表示贊賞。

我相信您的drop_id和box_id不是在JavaScript中選擇元素的正確方法。 老實說,也不太確定{{stuff}}模板發生了什么

可以使用jQuery嗎? 如果是這樣,請訪問http://www.w3schools.com/jquery/html_val.asp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM