Listbox options javascript select all,move left-right, move up-down

While working with Listboxes I had to write few small JavaScript snippets to perform certain tasks like selecting all options / seselecting all options or moving options up and down or swapping the options between two listboxes. I thought of sharing the JavaScript functions with you so that you can bookmark the article and use the code whenever you need them.

Listbox Select All / Deselect All JavaScript

Following is the JavaScript function for implementing select all, deselect all options in listbox.
function listbox_selectall(listID, isSelect) { var listbox = document.getElementById(listID); for(var count=0; count < listbox.options.length; count++) { listbox.options[count].selected = isSelect; } }
The above javascript code is very straight forward. All you have to do it to pass the ID of listbox you need to perform select all/deselect all and a boolean value for select/deselect. For example if a listbox has an id “countryList” following can be the function call.
listbox_selectall('countryList', true); //select all the options listbox_selectall('countryList', false); //deselect all the options

Listbox Move up/down options JavaScript

Following is the javascript function that you can use to add move up/down options functionality. User can select any option and move it up in the list or down.
function listbox_move(listID, direction) { var listbox = document.getElementById(listID); var selIndex = listbox.selectedIndex; if(-1 == selIndex) { alert("Please select an option to move."); return; } var increment = -1; if(direction == 'up') increment = -1; else increment = 1; if((selIndex + increment) < 0 || (selIndex + increment) > (listbox.options.length-1)) { return; } var selValue = listbox.options[selIndex].value; var selText = listbox.options[selIndex].text; listbox.options[selIndex].value = listbox.options[selIndex + increment].value listbox.options[selIndex].text = listbox.options[selIndex + increment].text listbox.options[selIndex + increment].value = selValue; listbox.options[selIndex + increment].text = selText; listbox.selectedIndex = selIndex + increment; }
Thus, you can call this function with first argument as list id and second argument a string value ‘up’ or ‘down’ depending on where you want to move the selected option.
listbox_move('countryList', 'up'); //move up the selected option listbox_move('countryList', 'down'); //move down the selected option

Listbox swap/move left-right options JavaScript

Following is the javascript code for moving selected options from one listbox to another.
function listbox_moveacross(sourceID, destID) { var src = document.getElementById(sourceID); var dest = document.getElementById(destID); for(var count=0; count < src.options.length; count++) { if(src.options[count].selected == true) { var option = src.options[count]; var newOption = document.createElement("option"); newOption.value = option.value; newOption.text = option.text; newOption.selected = true; try { dest.add(newOption, null); //Standard src.remove(count, null); }catch(error) { dest.add(newOption); // IE only src.remove(count); } count--; } } }
Just call the function with two arguments, first is the source listbox id and second is the destination listbox id.
listbox_moveacross('countryList', 'selectedCountryList');

Online Demo

Click here for the online demo.

Getting Values in Server side script

When you submit the form with Listbox, by default browser will submit only selected values from that selectbox. Thus if you want to submit values from right hand side select box, you first needs to select all those before form gets submitted. You can do this like below:
<script> function submit() { listbox_selectall('righthand_side_listbox_id', true); return true; } <form onsubmit="return submit()"> ... </form>
This would select all the options before form gets submitted. Now you can retrieve options in your server side script from request as request parameter.
Get our Articles via Email. Enter your email address.

You may also like...


  1. mangesh says:

    Thanks a lot.

  2. agniraj says:

    How can i get right side list when i submit

  3. Vivekanand says:

    Nice article, I am searching for the same using jQuery….

    And coming to the question which Agniraj has mentioned, Agniraj here is your answer, just check out the length of right list box and loop through the options, you will get all the options which are there in right list box.

    Hope this might :)


    • saurav says:

      when i am trying it is giving me error as The function add(___newOption0, null) is undefined for the type Element

  4. Ivan says:

    Gracias… no sabes del lio en que me sacaste…. te lo agradezco mucho.

  5. Thanks for the script, it helped me in right time to finish the project.

  6. basty_dread says:

    Please email me on how could i select all the values on the listbox if my listbox name is like this

    this is my javascript for selecting all the listbox items:

    function selectall()

  7. amit says:

    Nice article..

  8. Rohit says:

    May be this wil help full but i need add,remove, add all, and remove all otion i the list

  9. Omer says:

    Thank you very much just what i needed

  10. darla says:

    I noticed a few things while implementing this in PHP I’d like to share:

    1) If you provide a name property to the destination list box, the “name=” property has to be appended with ‘[]’ at the end, to return an array of items, otherwise it only returns the first item in the destination list box. For example

    Use: …
    Not: …

    2) In the script function “listbox_moveacross(sourceID, destID)”, the value of src.options.length needs to reflect the current sizeof src.options.length thru each iteration. In my implementation, I captured src.options.length into a local var ahead of the loop, in hopes of gaining some tick ecomony.

    So I did:
    var maxx = src.options.length;
    for(var count=0; count < maxx; count++)


    versus the example:
    for(var count=0; count < src.options.length; count++)


    I found out the hard way, I had to decrement var maxx along with the var count– decrement. So the code line after count–; became maxx–;

    if(src.options[count].selected == true)


    Just a lesson learned.

    • Darren says:

      Hi Darla,

      I have only just started programing and can not get the code you changed working for the select box more right. Can you post or e-mail me the javascript?
      How do I get the variables in PHP??
      $rightselect = mysql_real_escape_string($_POST[‘rightselect’]);
      ? My seclect id and name are rightselect
      Many thanks for your help!

  11. Saravanan says:

    Hi ,
    This code work fine in browsers except IE6.
    Let me explain. There is a bug that an empty entry is displayed if you do that following:-
    1. On the Online demo section, in the two list boxes on the right, select all the values from the extreme right listbox and move them to the left Listbox.
    2. You would see that a scroll bar is displyed.
    3. select say ‘Bhutan’ and scroll down until the selected ‘Bhutan’ is not visible.
    4. Click on the right arrows to move the value to the Extreme right Listbox.
    5. You would see a blank value in the Left Listbox when ‘Bhutan’ was originally there.
    6. Click on the Blank value and the value just below it is written on the blank giving duplicate values to the listbox.
    7. If you go on selecting the countries in the list, you would notice that all the value at the current position in the list would take the value of the next position and so on and os forth.

    I am experiencing the same in my code as well. It would be helpful if somebody could give pointers to resolve this issue.

  12. Victor says:

    Hi, great script.

    Does anyone know of a similar script that can handle images? What I want is for the user to be able to choose image priority that will later be displayed in an image scroller. Since option values dont allow for image tags my question is if something simliar to the above can be done perhaps with divs or something? Any help or suggestions are greatly appreciated.


  13. Ashwini says:

    Does anyone know how to delete multiple checked options using struts?I am able to delete single checked option.If i check multiple boxes,it deletes only 1.Any help or suggestions are greatly appreciated.

  14. emre says:


    Thank you very for script.i think it s awesome..I have checked the script in ie,firefox and chrome and i have not got errors. but when i have checked in opera 10.54, i came across an error..For example when you select items more than one and click move across button you will see just the first item is swapped so the others are not can i fix this problem..

    thanks for your help
    Best Regards

  15. Nishant says:

    Hi there,

    Thanks so much for this script. You saved a lot of my time.thanks again.

    all the best :)

  16. tinh.khau says:

    I used some other code for this in the past. But this is the best one with a very clean design.

  17. Ishfaq says:

    As i feel there is an enhancement required.
    On the double click event on any item from one select box it should be automatically passed to the other select box or vice versa.

  18. Ritam Atarthy says:

    thank you for thr fabulous code .

  19. jepoy says:

    thanks… simple amazing…
    save my time to code it.

  20. Dhananjay says:

    Superb Solution. The one thing i am only confused is what is

    “listbox_moveacross('s', 'd')”

    “listbox_moveacross('d', 's')

    “'s', 'd&#39”

  21. vissu says:

    var listbox = document.getElementById(listID);
    var src = document.getElementById(sourceID);
    var dest = document.getElementById(destID);

    getting listbox , src ,dest null, although listID,sourceID,destID getting values.

    • @vissu – See if your HTML page has select boxes with the appropriate IDs. It could be the only reason why getElementById method is unable to retrieve a DOM object.

  22. Ashraf says:

    How can i add limitation from right to left ? Please send me the solution.

    • @Ashraf: To add list items from right selectbox to left all you need to do is to call function listbox_moveacross() with argument first right listbox id and then left listbox id.

      listbox_moveacross(right_id, left_id);

      Hope that works.

  23. Selvi says:

    It’s nice. Thanks!!!

  24. zodehala says:

    how can i get “selectedCountryList” value from php files

    i can not get i t using following codes

    foreach($_POST as $a => $b)
    echo $a.” – “.$b.””;

  25. mesmerina says:

    how can i send data in right selectbox to php file

  26. Abhi says:

    This is very helpful. Thanks!

  27. sith says:

    This script runs correctly in google chrome ,but not in firefox !!!. Any solutions to solve this problem??

  28. sridevi says:

    can somebody help me how to save the data that is entered in the text boxes/checkboxex/radio button/listboxes in the html to excel sheet. I wanted to use these excel values to retrieve again from html to excel and vice versa.

  29. Jhane says:

    Could you help me on how i can move my record from one table to another using checkbox?..thank you for the big help

  30. Jhane says:

    I don’t know if I need these codes in order to move my record

    				url: "modules/delete-all.php",
    				data: "check"

    thank you for the help/

  31. AEG says:

    Awesome code, but I am confused as to how:
    var src = document.getElementById(sourceID);
    var dest = document.getElementById(destID);
    get associated when the tag ID’s are “s” and “d”.
    I’m not making the connection?

  32. Randi says:

    Thanks patel… your articles was helped me

  33. sri says:

    Thanks Sir.

  34. karthik says:

    Hi Viralpatel,

    In my webform i have taken two list boxes and two buttons to swap items from one list box to another list box.
    listbox_moveacross(‘countryList’, ‘selectedCountryList’);can you please tell the event name to call this in listboxes.
    i have used onclick event iam calling this function its working but i have swap items in in button click event can you please help me in which events i have to call this function listbox_moveacross(‘countryList’, ‘selectedCountryList’);


  35. vamsi boppana says:

    This code is working in my local browser, but once i depoy it in server started showing error:
    “dest.add(newOption, null); //Standard”
    Nice article but check this issue too.
    this issue ate one day time of mine.

  36. John says:

    Firstly its a very good piece of code..kudos to the attempt.
    But,I’m afraid to say that there is a logical error in the code..
    we cannot move up or down 2 or more options at a time.Only the first selected option comes up.
    If you can make it for the issue..will be very helpful…
    Thank you in advance…. :)

  37. Really useful snippets. Thanks

  38. Mallesh M says:

    Nice Article, i was looking for the same and saved a lot of time.

  39. Sipho M says:

    Hi there

    You saved me a couple of hours.
    Great work, Keep it up

  40. Milan M says:

    Very nice Article, i was looking for the same.

  41. Shruthi says:

    Can you please send me the full html code for CountryList Selection…I am new to html so please help me with this..

  42. Shruthi says:

    Hi, Can you please tel me how to open QTP using javascript code…

  43. Sandaruwan says:

    Thanks! Very useful. did some changes and arranged according to my needs.

    • praveen kumar vk says:

      Any please give a solution to load listbox value dyanamically? please provide the code

  44. praveen kumar vk says:




    javascript function

    function listbox_moveacross(sourceID, destID) {
        var src = document.getElementById(leftcombo);
        var dest = document.getElementById(rightcombo);
        for(var count=0; count &lt; src.options.length; count++) {
            if(src.options[count].selected == true) {
                    var option = src.options[count];
                    var newOption = document.createElement(&quot;option&quot;);
                    newOption.value = option.value;
                    newOption.text = option.text;
                    newOption.selected = true;
                    try {
                             //dest.add(newOption, null); //Standard
                             //src.remove(count, null);
                             dest.add(newOption); //Standard
                     }catch(error) {
                             dest.add(newOption); // IE only

    Hi anyone can explain the problem in this code
    i am geeting exception like my web page is getting expired while adding the values from first list box to next list box in IE8
    any one please give me a solution with code

  45. praveen says:

    Any one please tell me how to avoid duplicate records while moving left combo box to right combo box in javascript?

  46. praveen says:

    Any one provide a solution to avoid duplicate records while moving records from left list box to right list box in javascript

  47. Srihari says:

    Your code saved a lot of time for me…
    Keep up the good work..

  48. Vinayak Ingulkar says:

    For Listbox swap/move left-right options JavaScript
    I am getting below error while adding the record to destination .
    htmlfile:Invalid argument .

    $("#SelectDataCarrier").click(function () {
            var src = document.getElementById("ava_datacarrier");
            var dest = document.getElementById("select_datacarrier");
            for (var count = 0; count &lt; src.options.length; count++)
                if (src.options[count].selected == true)
                    var option = src.options[count];                   
                    var newOption = document.createElement(&quot;option1&quot;);  
                    newOption.value = option.value;                
                    newOption.text = option.text;                 
                    //newOption.selected = true;                
                        dest.add(newOption, null); //Standard                         
                        src.remove(count, null);                  
                        dest.add(newOption); // IE only                         

    @using Kendo.Mvc.UI.Fluent
    @using Kendo.Mvc.Resources
    @model  ApplicationManagement.Web.Models.ApplicationDataCarrierViewModel  
        Layout = &quot;&quot;;
        @*Data Carrier*@ 
                 @*  @(Html.Kendo().MultiSelect()
                            .Placeholder("Select DataCarrier...")
                            )    *@
                   @*   @(Html.Kendo().MultiSelect()
                            .Placeholder("Selected DataCarrier...")
                            )  *@   
                    Data-Carrier Available                 
                            var listItemsCat0 = new List();
                            foreach (var datacarrier in Model.DataCarriers)
                                listItemsCat0.Add(new SelectListItem { Text = datacarrier.Description, Value = (string)datacarrier.DataCarrierId.ToString() });
                             @(Html.ListBox("ava_datacarrier",  listItemsCat0,new {@style = "width:200px; "}))                                
                    Data-Carrier Selected                             
                        var listItemsCat1 = new List();
                        foreach (var appdatacarrier in Model.ApplicationDataCarriers)
                            //listItemsCat1.Add(new SelectListItem { Text = datacarrier.Description, Value = (string)datacarrier.DataCarrierId.ToString() });
                              listItemsCat1.Add(new SelectListItem { Text = appdatacarrier.DataCarrier.Description, Value = (string)appdatacarrier.DataCarrier.DataCarrierId.ToString() });
                             @(Html.ListBox("select_datacarrier", listItemsCat1 ,new {@style = "width: 200px;"   }))                  
                     @Html.Hidden("Appid", Model.ApplicatationID)   
                        var listItemsCat2 = new List();                
                       listItemsCat2.Add(new SelectListItem { Text = "-1", Value = "-1" });
                             @(Html.ListBox("delete_datacarrier", listItemsCat2,new {@style = "width: 20px; display : none;"}))                  

  49. Vimal Kanzariya says:

    Thank you, Thank you, Thank you, Thank you very much…

  50. Allie says:

    here is my code but that move all time main category loop forward

    function selectItems(fromID,toID)
    var from = document.getElementById(fromID);
    var to = document.getElementById(toID);

    if(from.selectedIndex == -1)
    return (false);

    //if(parentNode.label == selectedIndex )

    for(var i=0; i = 0; i–)
    var o=from.options[i];


    function find(val,idx) {
    var sel=document.getElementById(‘lstboxItems’);

    var s=val+’ : ‘+sel.options[idx].parentNode.label;


    $str2="Select * from list_task where pid=0";
    $res2=mysql_query($str2) or die(mysql_error());
    echo "”;
    $str3=”select * from list_task where pid='”.$row[0].”‘”;
    $res3=mysql_query($str3) or die(mysql_error());
    echo “$row2[2]”;

    echo “”;


    • Allie says:

      please help ma fast

  51. Praveen says:

    How to move all values in one button click? I tried calling the add function in select all function but it didnt work. I need add all and remove all buttons along with these functionality. Kindly help!

  52. Ron says:

    Very nice code and clever ideas.
    Here is a variation (just for the heck of it)

    	<STYLE type="text/css">
    	body { font-family:Arial; }
    	a { color:#00f; text-decoration:none; }
    	<SCRIPT type="text/javascript">
    	function listbox_move(listID,direction){
    	var listbox=document.getElementById(listID);
    	var selIndex=listbox.selectedIndex;
    	if(-1==selIndex){alert("Please select an option to move.");return;}
    	var increment=-1;
    	var selValue=listbox.options[selIndex].value;
    	var selText=listbox.options[selIndex].text;
    	function listbox_moveacross(sourceID,destID){
    	var src=document.getElementById(sourceID);
    	var dest=document.getElementById(destID);
    	var picked1 = false;
    	for(var count=0;count<src.options.length;count++){
    	if(picked1==false){alert("Please select an option to move.");return;}
    	for(var count=0;count<src.options.length;count++){
    		if(src.options[count].selected==true){var option=src.options[count];
    			var newOption=document.createElement("option");
    	function listbox_selectall(listID,isSelect){
    		var listbox=document.getElementById(listID);
    		for(var count=0;count<listbox.options.length;count++){
    	<TITLE>Listbox JavaScript functions</TITLE>
    <table border="1" align="center" style="border-collapse:collapse;">
    <td colspan="5" align="center"><font size="+2"><b>Listbox Functions</b></font></td>
    <tr valign="top">
    <th>Move up/down</th>
    <th colspan="3">Move left/right</th>
    <tr valign="top">
    <SELECT id="a" size="10" multiple>
    	<OPTION value="a">Afghanistan</OPTION>
    	<OPTION value="b">Bahamas</OPTION>
    	<OPTION value="c">Barbados</OPTION>
    	<OPTION value="d">Belgium</OPTION>
    	<OPTION value="e">Bhutan</OPTION>
    	<OPTION value="f">China</OPTION>
    	<OPTION value="g">Croatia</OPTION>
    	<OPTION value="h">Denmark</OPTION>
    	<OPTION value="i">France</OPTION>
    	<OPTION value="j">Canada</OPTION>
    <SELECT id="s" size="10" multiple>
    	<OPTION value="a">Afghanistan</OPTION>
    	<OPTION value="b">Bahamas</OPTION>
    	<OPTION value="c">Barbados</OPTION>
    	<OPTION value="d">Belgium</OPTION>
    	<OPTION value="e">Bhutan</OPTION>
    	<OPTION value="f">China</OPTION>
    	<OPTION value="g">Croatia</OPTION>
    	<OPTION value="h">Denmark</OPTION>
    	<OPTION value="i">France</OPTION>
    	<OPTION value="j">Canada</OPTION>
    <td valign="middle">
    <a href="#" onclick="listbox_moveacross('s', 'd')">►</a>
    <a href="#" onclick="listbox_moveacross('d', 's')">◄</a>
    <SELECT id="d" size="10" multiple>
    	<OPTION value="a">Albania</OPTION>
    	<OPTION value="b">Bohemia</OPTION>
    	<OPTION value="c">Brazil</OPTION>
    	<OPTION value="d">Bhutan</OPTION>
    	<OPTION value="e">Bolivia</OPTION>
    	<OPTION value="f">Chile</OPTION>
    	<OPTION value="g">Cuba</OPTION>
    	<OPTION value="h">Djibouti</OPTION>
    	<OPTION value="i">Finland</OPTION>
    	<OPTION value="j">Greece</OPTION>
    Move <a href="#" onclick="listbox_move('a', 'up')">▲ up</a>,
    <a href="#" onclick="listbox_move('a', 'down')">▼ dn</a>
    <a href="#" onclick="listbox_selectall('a', true)">all</a>,
    <a href="#" onclick="listbox_selectall('a', false)">none</a>
    <a href="#" onclick="listbox_selectall('s', true)">all</a>,
    <a href="#" onclick="listbox_selectall('s', false)">none</a>
    <a href="#" onclick="listbox_selectall('d', true)">all</a>,
    <a href="#" onclick="listbox_selectall('d', false)">none</a>

    • Deepak says:

      Thanks for the code. It works fine on IE9, however it doesn’t work on IE11.
      Use case:
      1. Select any option
      2. Move up or down
      3. Try selecting other option in same box, you will not be able to select other option.

      I am facing similar issue while migrating to IE11. Please help! Thanks in advance.

    • Deepak says:

      The code snippet which Ron has posted doesn’t work on IE11. Can someone please reply with the fix. I am facing similar issue while migrating to IE11.

      Use case:
      In IE11:
      1. Select one option and move up or down
      2. Select other option to move, however the option can’t be selected.

      Any help would be appreciated. Thanks.

    • Rani says:

      Thank You so much

  53. Mojgan says:

    Hi everyone,

    This is a great script! Does anyone have a fix for IE7 and IE6? I am getting JavaScript error and this is rather urgent.

    Much appreciated,
    Mojgan Nemati
    [email protected]

  54. Radhika says:

    Hi Viral

    Can you help me the same logic to be inserted as a javascript in cognos report

  55. F. Paepke says:

    I have a lot of items in my listbox and so I added a link ‘TOP’ that uses your up-function to place the selected item to the top of the listbox

    function listbox_move(listID,direction)
    	var listbox=document.getElementById(listID);
    	var selIndex=listbox.selectedIndex;
    		alert("Please select an option to move.");
    	var increment=-1;
    	var selValue=listbox.options[selIndex].value;
    	var selText=listbox.options[selIndex].text;
    	if(direction=='up' || direction=='down')
    		for(var count=0;count&lt;listbox.options.length;count++)
    			listbox_move(&#039;a&#039;, &#039;up&#039;);

  56. Toba says:

    so how do you submit selected items to database

  57. Luis Rodriguez says:

    hola no me funciona el selected index , no hay forma de que despues de llenar el list box se me marque el primer item , solo si voy con el mouse , pero en automatico no hay vida , nada de lo que esta publicado en internet sirve , quizas le sirva a otros porque tendran alguna magia que no han publicado o algun truco que no quieren decir

  58. PKT says:

    Up and Down listbox got hanged in IE11 after up and down item very fast (Can’t select any item manually in first lsitbox in your demo). Any idea how to resolve

  59. Justel says:

    A Move Version that works:

    function listbox_move(listID,direction)
    	var listbox=document.getElementById(listID);
    	var iLstL=listbox.length, iSelIndO=listbox.selectedIndex, iSelIndN=iSelIndO+((direction=="Up")?-1:1);
    	if(iLstL<1 || iSelIndO==-1 || iSelIndN < 0 || iSelIndN > (iLstL-1)) return;
    	var oIsSel = listbox.options[iSelIndO].cloneNode(true);
    	listbox.options[iSelIndO] = listbox.options[iSelIndN].cloneNode(true);
    	listbox.options[iSelIndN] = oIsSel.cloneNode(true);
    	listbox.options[iSelIndN].selected = true;

  60. Aishy says:

    Very useful article. Thanx a lot.
    I’m doing a HTML/javascript project and there’s a list box called ‘newlist’.
    list box items are coming from the database.
    Can you please let me know, how can I delete only the first item and the last item from this list box?

  61. kiruthiga says:

    In IE11:
    1. Select any one option and move up or down very fastly.
    2. Select other option to move, however the option can’t be selected

    Add the below code in move up and down function

  62. Divya says:

    Thanks for the solution

  63. Mahadev says:


    I am new to javascript. i have created one page using php and javascript. my requirement is i have a csv file, it’s having bunch of name and mail id’s. for eg:

    cat list.csv.
    name1,[email protected]
    name2,[email protected]
    name3, [email protected]

    in my php page having 4 fields,
    company code
    employee id

    In “name” field I can display the first field of csv contents as it’s having name. (please note that name field is a multiselect drop down box). If I select “name1” immideately name1 mail id ([email protected]) should appear in “mailid” column without any submit button. If I select both “name1” and “name2” immediately [email protected] and [email protected] mailid’s should appear in “mailid” field.

    I used “relaod(this.form)” option for name field, but it will be reload the page immediately once I select single name. it’s not allowing me to select multiple names.

    I used “relaod(this)” option for name field, only name values I can get after rload the page “company code” and “employee id” values will be disappear.

    Could anyone please help me on this.

    Thanks in advance,


  64. Jimmy says:

    Great code! Thanks for posting. In the move across code, is there a way place the item on the TOP of the list instead of the bottom?

  65. Jimmy says:

    Answered my own question, just needed to set the dest.add newOption to 0 and not null.

  66. Sajeev M V says:

    Thank you for the code. Superb

  67. Mohankumar says:


    With the single list, if I select a value and click on up/down, the selected element is getting moved but getting freezes in Internet Explorer. Hence, not able to select another element in the list. Can you pls resolve and let us know??

  68. Ankit Bikers says:

    Can I create a kind of list on which If I click on any item (in the left list) it automatically moves to right side?
    If I click on any item (in the Right list) it automatically moves to Left side?

Leave a Reply

Your email address will not be published. Required fields are marked *