[英]Adding new options to multiple select elements issue
我有一個表格,用戶可以選擇幾個想要停留的地點,他們必須指定要在每個地點停留的時間,但首先,他們必須輸入每個地點通常要停留多少天,例如,如果我想在兩個地點的第一個地點停留2天,在第二個地點停留3天,則必須先輸入5天,然后選擇要停留的地點,為每個地點指定我要停留多少天想要在那里。 好是為了防止用戶為某個位置輸入錯誤的天數,我為每個位置創建了一個選擇元素,因此當用戶輸入一般天數時,我用該信息填充了選擇元素(從1開始的選項到天數),這很好,但是當用戶選擇一個位置並指定該位置的天數時,我希望其余的選擇元素都填充剩余的天數,因此我使用此代碼來執行此操作
function fillUpSelects2(start, top, who) {
var optionArray = new Array();
// create the new options
for (var i = 1; i <= top; i++) {
optionArray.push(new Option(i, i));
}
// get all the select elements
var selects = jQuery("select.estanciaselect");
// loop through the selects to change their content
for (var i = 0; i < selects.length; i++) {
// if selects[i] is not the one who triggered the change event
if (selects[i].getAttribute('id') != who) {
// then I erase all its options
selects[i].options.length = 0;
//and here is where it is supposed to add the new options
for (var j = 0; j < optionArray.length; j++) {
selects[i].options[selects[i].options.length] = optionArray[j];
}
}
}
}
好吧,當我運行此選項時,所有選擇最終都為空,但最后一個被正確填充
如果您使用的是jQuery,則最好使用它來附加它們:
for (var i = 1; i <= top; i++) {
$(".selects").prepend($("<option>")
.val(i) // Might have to use .attr("value", i) instead
.html(i));
}
這是一個jsFiddle,展示了可以使用的兩個選項(包括上面的一個),但是還有更多選擇:
以下是有關如何添加項目以進行多選的方法(盡管不是您問題的直接答案)
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var o = new Option("option text", "value");
$(o).html("option text");
$("#leftValues").append(o);
});
</script>
<select id="leftValues" size="5" multiple></select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.