从选定的下拉菜单项中应用文本到输入字段(html,javascript)

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

本文关键字:字段 输入 html javascript 文本 应用文 应用 菜单项      更新时间:2023-09-26

当我从下拉菜单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