當我從一個下拉列表中選擇一個項目,像在輸入字段中查看它,如果選擇了另一個項目,我想將其添加到輸入字段分隔以逗號分隔。從選定的dropdownmenu項應用文本到輸入字段(html,javascript)
目前這是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屬性altough的代碼似乎是合乎邏輯給我。這是我第一次寫JavaScript,所以它很可能是我錯過了一些微不足道的東西。任何幫助都是令人滿意的。
您必須使用選定選項的'.value',而不是'.text'。 – Moo
@Moo感謝您的提示,但我仍然得不到任何東西:/ – Bonbin