Pages

Tuesday 11 March 2014

Moving Item from one listbox to other and visversa using Javascript


/*Here is two listbox and two buttons >> to move selected items to right and <<  to move selected items to left On button click we called Javascript function moveToRightOrLeft*/
@Html.ListBox("channels", ViewBag.channels as MultiSelectList,
new { size = "6", id = "selectLeft" })
<input name="btnRight" type="button" id="btnRight" value="&gt;&gt;" onclick="javaScript:moveToRightOrLeft(1);">
<input name="btnLeft" type="button" id="btnLeft" value="&lt;&lt;" onclick="javaScript:moveToRightOrLeft(2);">
@Html.ListBox("channelSelected", new List<SelectListItem>(), new { size = "6", id = "selectedChannelList" })
/*listleft is left side Listbox and  listRight is right side listbox*/
<script type="text/kavascript">
function moveToRightOrLeft(side) {
var listLeft = document.getElementById('selectLeft');
var listRight = document.getElementById('selectedChannelList');
if (side == 1) {
if (listLeft.options.length == 0) {
alert('You have already moved all channels to Right');
return false;
} else {
var selectedChannel = listLeft.options.selectedIndex;
move(listRight, listLeft.options[selectedChannel].value, listLeft.options[selectedChannel].text);
listLeft.remove(selectedChannel);
if (listLeft.options.length > 0) {
listLeft.options[0].selected = true;
}
}
} else if (side == 2) {
if (listRight.options.length == 0) {
alert('You have already moved all channels to Left');
return false;
} else {
var selectedChannel = listRight.options.selectedIndex;
move(listLeft, listRight.options[selectedChannel].value, listRight.options[selectedChannel].text);
listRight.remove(selectedChannel);
if (listRight.options.length > 0) {
listRight.options[0].selected = true;
}
}
}
}
function move(listBoxTo, optionValue, optionDisplayText) {
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
</script>

No comments:

Post a Comment