Madalina Cristina Madalina Cristina - 13 days ago 7
Javascript Question

move element from a list to another list and inverse javascript

I want to move items from the first list in the second and vice versa. First works.
I tried to write for second list,but it doesn't work and i don't know why.
Could someone help me?
This is what i tried to do.

<html>
<head>
<script>
function moveRight() {
var selItem = document.forms[0].leftList.selectedIndex;
if (selItem == -1) {
window.alert("You must first select an item on the left side.")
} else {
document.forms[0].rightList.add(document.forms[0].leftList[selItem], null);
}
}
function moveLeft(){
var selItem=document.forms[1].leftRight.selectedIndex;
if (selItem == -1) {
window.alert("You must first select an item on the right side.")
} else {
document.forms[1].leftList.add(document.forms[1].rightList[selItem], null);
}
}
</script>
</head>
<body>
<form name="form1" onsubmit="return false;">
<select name="leftList" multiple="multiple">
<option value="item1">Item1</option>
<option value="item2">Item2</option>
<option value="item3">Item3</option>
<option value="item4">Item4</option>
</select>
<select name="rightList" multiple="multiple">
<option value="elem1" > Elem1</option>
<option value="elem2">Elem2</option>
</select>

<button onclick="moveRight()">Move to the right</button>
<button onclick="moveLeft()">Move to the left</button>
</form>
</body>
</html>

Answer

There are 2 issues

1: There is no forms[1] element it should be forms[0] only.

2: document.forms[1].leftRight is no elemnt it should be document.forms[0].rightList

function moveLeft(){
  var selItem=document.forms[0].rightList.selectedIndex;
  if (selItem == -1) {
      window.alert("You must first select an item on the right side.")
  } else {
      document.forms[0].leftList.add(document.forms[0].rightList[selItem], null);
  }
}

Working example: https://plnkr.co/edit/uw28oLtQBjfW9vS0d5ld?p=preview

Comments