美好的一天。將元素從列表框移動到另一個
我需要這樣做。我有2個列表框,當按下按鈕時,我需要將選項從一個移動到另一個。
我這樣做:
HTML:
<table border="1" cellpadding="5">
<tr>
<td>
Un-Selected <br />
<select multiple="multiple" id="selectBoxOne" size="5" class="selectListBox">
<option value="0" id="multiple0">Option 0</option>
<option value="1" id="multiple1">Option 1</option>
<option value="2" id="multiple2">Option 2</option>
<option value="3" id="multiple3">Option 3</option>
<option value="4" id="multiple4">Option 4</option>
<option value="5" id="multiple5">Option 5</option>
</select>
<br />
<input type="checkbox" id="selectAllFirst"/>Select All or Ctrl+Click
</td>
<td>
<div onclick="move('left');"> << </div>
<div onclick="move('right');"> >> </div>
</td>
<td>
Selected <br />
<select name="policyCode" multiple="multiple" id="selectBoxSecond" size="5" class="selectListBox">
</select>
<br />
<input type="checkbox" id="selectAllSecond"/>Select All or Ctrl+Click
</td>
</tr>
</table>
的javascript:
// Declare elements
var selectOptions = Array();
selectOptions[0] = "Option 0";
selectOptions[1] = "Option 1";
selectOptions[2] = "Option 2";
selectOptions[3] = "Option 3";
selectOptions[4] = "Option 4";
selectOptions[5] = "Option 5";
// function to move an element from a box to the other
function move(sens)
{
if (sens == "right")
{
var selObj = document.getElementById('selectBoxOne');
var chkAll = document.getElementById("selectAllFirst")
var destination = document.getElementById("selectBoxSecond");
}
else
{
var selObj = document.getElementById('selectBoxSecond');
var chkAll = document.getElementById("selectAllSecond")
var destination = document.getElementById("selectBoxOne");
}
var selectedArray = new Array();
var i;
var count = 0;
if (chkAll.checked == 1)
{
for (i = 0; i<selectOptions.length; i++)
{
selectedArray[i] = i;
}
}
else
{
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
}
for (i = 0; i < selectedArray.length; i++)
{
var optionTag = document.createElement("option");
id = selectedArray[i];
optionTag.innerHTML = selectOptions[id];
optionTag.value = id;
optionTag.id = "multiple"+id;
destination.appendChild(optionTag);
var rmv = document.getElementById("multiple"+id);
rmv.parentNode.removeChild(rmv);
}
}
現在:劇本從左側框移動到右邊框的偉大工程。但是當我以相反的方式嘗試時,會發生崩潰。沒有錯誤返回,但我知道肯定是刪除部分(如果我評論它工作正常...除了它會生成重複,因爲沒有刪除移動的選項)。
更具體地說,這2行: var rmv = document.getElementById(「multiple」+ id); rmv.parentNode.removeChild(rmv);
由於沒有錯誤返回,我不知道如何解決這個問題。任何幫助嗎?
問:你有沒有試圖把在第二循環的「刪除」:直到你添加完,先不要刪除任何東西? – paulsm4