[英]need help in adding options to select using javascript
我的頁面布局如下所示,因為我有表單,因此需要在<select>
設置值。
<form action="add.jsp">
<input name="title" id="title"/>
<input name="company" id="company" />
<select name="options" id="options">
</select>
<button>Submit</button>
</form>
我想從表單外面的復選框的<select/>
上面添加值
<input id="input-checkbox-1" name="input-checkbox" type="checkbox">Option 1
<input id="input-checkbox-2" name="input-checkbox" type="checkbox">Option 2
<input id="input-checkbox-3" name="input-checkbox" type="checkbox">Option 3
現在對如何從復選框獲取值以及添加使用jQuery選擇的選項一無所知。
現在對如何從復選框獲取值以及添加使用jQuery選擇的選項一無所知。
首先,要獲取HTML元素,可以使用$("css selector")
, document.getElementById("id value")
或document.querySelector("css selector")
。
這是CSS選擇器語法參考: http : //www.w3.org/TR/selectors/#selectors
接下來,要檢索復選框的值, .checked
元素的.checked
屬性。 這將是true
,如果選中該復選框和false
,否則。
document.querySelector("input").addEventListener("change",function(){ alert(this.checked); });
<input type="checkbox" />Check me
最后,要將值添加到select
元素,請創建一個option
元素,設置其文本和值,然后將其添加到select
。
var select = document.querySelector("select"); var checkboxes = document.querySelectorAll('[type="checkbox"]'); for(var i = 0, len = checkboxes.length; i < len; i++){ checkboxes[i].addEventListener("change",addOrRemoveMe); } function addOrRemoveMe(){ if(this.checked){ var option = document.createElement("option"); option.value = this.name; option.text = this.name; select.appendChild(option); }else{ select.removeChild(select.querySelector('[value="'+this.name+'"]')); } }
<input type="checkbox" name="One"/> One<br/> <input type="checkbox" name="Two"/> Two<br/> <input type="checkbox" name="Three"/> Three<br/> <select></select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.