Tuesday, November 21, 2006

How to move selected items from one select box to another using Javascript?

//to move selected items from one select box to another
function move(fbox, tbox) {

var arrFbox = new Array();
var arrTbox = new Array();
var arrLookup = new Array();
var i;
if(fbox.options.length==0) {
alert('No items available to move');
return false;
}
for (i = 0; i < tbox.options.length; i++) {
arrLookup[tbox.options[i].text] = tbox.options[i].value;
arrTbox[i] = tbox.options[i].text;
}
var fLength = 0;
var sLength = arrTbox.length;
var tLength = arrTbox.length;
for(i = 0; i < fbox.options.length; i++) {
arrLookup[fbox.options[i].text] = fbox.options[i].value;
if (fbox.options[i].selected && fbox.options[i].value != "") {
arrTbox[tLength] = fbox.options[i].text;
tLength++;
}
else {
arrFbox[fLength] = fbox.options[i].text;
fLength++;
}
}
if(sLength == tLength) {
alert('Please select atleast one');
return false;
}

arrFbox.sort();
arrTbox.sort();
fbox.length = 0;
tbox.length = 0;
var c;
for(c = 0; c < arrFbox.length; c++) {
var no = new Option();
no.value = arrLookup[arrFbox[c]];
no.text = arrFbox[c];
fbox[c] = no;
}
for(c = 0; c < arrTbox.length; c++) {
var no = new Option();
no.value = arrLookup[arrTbox[c]];
no.text = arrTbox[c];
tbox[c] = no;
}
}

//Usage
<select multiple size="5" name="SB1[]" id="SB1">
<option>1</option><option>2</option>3<option></option>4<option></option><option>5</option>
</select>

<input type="button" onClick="move(this.form.SB1,this.form.SB2)" value=">>">
<input type="button" onClick="move(this.form.SB2,this.form.SB1)" value="<<">

<select multiple size="5" name="SB2[]" id="SB2"></select>

No comments: