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.



43 Comments

  • mangesh 16 July, 2009, 16:34

    Thanks a lot.

  • agniraj 8 August, 2009, 19:08

    How can i get right side list when i submit

  • Vivekanand 13 August, 2009, 23:25

    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 :)

    Thanks,
    Vivek

    • saurav 23 August, 2011, 11:56

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

  • Ivan 29 August, 2009, 2:43

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

  • Bhoobala Krishnan B 8 October, 2009, 17:15

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

  • basty_dread 30 October, 2009, 8:55

    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()
    {
    for(i=0;i<document.forms['frmcustom'].sections[].length;i++){
    document.forms['frmcustom'].sections[i].selected=true;     
    }
    } 
  • amit 10 November, 2009, 18:56

    Nice article..

  • Rohit 26 February, 2010, 11:49

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

  • Omer 14 March, 2010, 16:27

    Thank you very much just what i needed

  • darla 24 April, 2010, 22:08

    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)
    {

    count–;
    maxx–;
    }

    Just a lesson learned.

    • Darren 28 February, 2013, 20:22

      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!

  • Saravanan 11 June, 2010, 11:02

    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.

  • Victor 15 June, 2010, 16:20

    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.

    Tx,
    Victor.

  • Ashwini 25 June, 2010, 9:23

    Hi….
    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.
    Thanks,
    Ashwini

  • emre 29 June, 2010, 17:29

    Hi,

    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 swapped..how can i fix this problem..

    thanks for your help
    Best Regards

  • Nishant 8 July, 2010, 23:05

    Hi there,

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

    all the best :)

  • tinh.khau 6 August, 2010, 20:11

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

  • Ishfaq 3 January, 2011, 14:31

    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.

  • Ritam Atarthy 28 March, 2011, 14:55

    thank you for thr fabulous code .

  • jepoy 19 July, 2011, 15:11

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

  • Dhananjay 30 August, 2011, 18:07

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

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

    “listbox_moveacross('d', 's')

    “'s', 'd&#39″

  • vissu 1 December, 2011, 14:31

    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.

    • Viral Patel 1 December, 2011, 14:37

      @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.

  • Ashraf 22 December, 2011, 22:45

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

    • Viral Patel 22 December, 2011, 23:39

      @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.
      e.g

      listbox_moveacross(right_id, left_id);
      

      Hope that works.

  • Selvi 27 December, 2011, 15:05

    It’s nice. Thanks!!!

  • zodehala 4 February, 2012, 20:37

    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.”";

  • mesmerina 6 February, 2012, 3:02

    how can i send data in right selectbox to php file

  • Abhi 19 July, 2012, 18:39

    This is very helpful. Thanks!

  • sith 22 September, 2012, 12:41

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

  • sridevi 29 September, 2012, 0:02

    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.

  • Jhane 8 November, 2012, 14:06

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

  • Jhane 8 November, 2012, 14:11

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

                                   $.ajax({
    				url: "modules/delete-all.php",
    				type:"get",
    				async:false,
    				data: "check"
    

    thank you for the help/

  • AEG 19 November, 2012, 21:41

    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?

  • Randi 23 November, 2012, 15:58

    Thanks patel… your articles was helped me

  • sri 28 January, 2013, 15:10

    Thanks Sir.

  • karthik 29 January, 2013, 17:25

    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’);

    Thanks,
    karthik

  • vamsi boppana 1 February, 2013, 12:11

    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.

  • John 20 February, 2013, 19:07

    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…. :)

  • Charlie Markwick 28 February, 2013, 19:30

    Really useful snippets. Thanks

  • Mallesh M 13 March, 2013, 1:11

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

  • Sipho M 4 April, 2013, 19:26

    Hi there

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

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]