Select content from one list to another using jQuery

List Content Selection using jQuery

List Content Selection using jQuery

Few days back I was searching for some JavaScript functionality in which we can drag and drop elements from one list to another. I have found few good examples but all of them have some limitations. Like few are not working in IE or not fit for my requirement.

So, I have decided to write one myself. I have used jQuery JavaScript library because its provide some cool functions to easily work with DOM.

The example is easy to understand and you can easily extend or change it as per your need. I have tested it in Firefox 3.0, Google Chrome 1.0, Safari 3.3.2 and IE 7.0 on windows platform.

What I did is I have created two DIVs. First DIV have all the items when page load. User can select multiple items from first DIV using checkbox and click the right button to move the selected items from first DIV to second DIV. They can also move item from right DIV to left DIV using the left button.

You can view the working demo here.

You can download the source code here.

Here is the code for it with explaination:

HTML:

<div id=”all_users”>
	<div id=”user1″ userid=1class=”innertxt”>
        <img src=”images.jpg” width=75height=75″><strong>Test User 01</strong>
        <ul>
            <li>User ID: 1</li>
            <li>Email: user1@nodomain.com</li>
            <li style=”padding-top:5px;”><input type=”checkbox” id=”select1″ value=1class=”selectit” />
                <label for=”select1″>&nbsp;&nbsp;Select it.</label>
            </li>
        </ul>
    </div>
</div>
<div>
	<a href=”javascript:void(0);” id=”move_right”>Right &raquo;</a><br /><br />
	<a href=”javascript:void(0);” id=”move_left”>&laquo; Left</a>
</div>
 
<div id=”selected_users”></div>

We have two DIVs with ID “#all_users” and “#selected_users“. “#all_users” contains all the items and “#selected_users” is empty when page load. The first DIV contain an item”#user1“. We also have two links “#move_left” and “#move_right” for moving items between lists.

JavaScript:

<script type="text/javascript">
$(’#all_users .selectit).click(function() {
	var userid = $(this).val();
	$(’#user’ + userid).toggleClass(’innertxt_bg’);
});
</script>

When user check the “select it” checkbox of any item we add the “.innertxt_bg” class to that item. When user unchecked any “select it” checkbox we remove the “.innertxt_bg” class from that item. This is done by “toggleClass()” method. “toggleClass()” method first check the given class is assigned to element, if class is assigned then its remove it otherwise assign to element.

<script type="text/javascript">
$(”#move_right”).click(function() {
	var users = $(’#selected_users .innertxt2).size();
	var selected_users = $(’#all_users .innertxt_bg).size();if (users + selected_users > 5) {
		alert(’You can only chose maximum 5 users.’);
		return;
	}
 
    $(’#all_users .innertxt_bg).each(function() {
        var user_id = $(this).attr(’userid’);
        $(’#select’ + user_id).each(function() {this.checked = false;});
 
        var user_clone = $(this).clone(true);
        $(user_clone).removeClass(’innertxt’);
        $(user_clone).removeClass(’innertxt_bg’);
        $(user_clone).addClass(’innertxt2′);
 
        $(’#selected_users’).append(user_clone);
        $(this).remove();
	});
});
</script>

When user clicks the “move right” button, We check which items are selected in first list. All the selected item have the class “.innertxt_bg”. Then we create the clone of selected item using the jQuery “clone()” method and append this clone at the end of second list. After appending the clone to second list we remove the actual item from first list using the “remove()” method. We are also implementing the limit in selection of number of items from first list. We are using “size()” method to find the number of selected items.

<script type="text/javascript">
$(”#move_left”).click(function() {
	$(’#selected_users .innertxt_bg).each(function() {
        var user_id = $(this).attr(’userid’);
        $(’#select’ + user_id).each(function() {this.checked = false;});var user_clone = $(this).clone(true);
        $(user_clone).removeClass(’innertxt2′);
        $(user_clone).removeClass(’innertxt_bg’);
        $(user_clone).addClass(’innertxt’);
 
        $(’#all_users’).append(user_clone);
        $(this).remove();
	});
});
</script>

When user clicks the “move left” button, we just do exactly same what we did in case of “move right” click. The difference is we move item from right list to left list and doesn’t check the number of selected items as there is no need of it.

<script type="text/javascript">
$(’#view’).click(function() {
	var users =;
	$(’#selected_users .innertxt2).each(function() {
		var user_id = $(this).attr(’userid’);
		if (users ==)
			users += user_id;
		else
			users +=,+ user_id;
	});
	alert(users);
});
</script>

When user click the “view” button we will collect all the item IDs from the right list and display it to user using “alert()” method. You can send the selected item information to server using AJAX or you can assign it to a hidden field and submit the form.

You can view the working demo here.

You can download the source code here.


,


  1. #1 by Nour - April 23rd, 2009 at 00:56

    Hoi i want to use your script ‘Select content from one list to another using jQuery’. I have integrated in my form. But can ik assign it to a hidden field and submit? I have done this “” but it don’t work.

    Thank you

  2. #2 by admin - April 23rd, 2009 at 12:35

    Hi Nour,

    Thanks for showing interest in my script. What you are doing to assigning the selected users in hidden field is not correct.
    Actually, the ‘#view’ is the ID of button and I have assigned a click event on this button using jQuery. And you are using this ID for hidden field.

    What you need to do is assign a different ID say ‘users’ to your hidden field.

    <input type=”hidden” name=’users’ id=”users”/>

    Then code it like this.

    $(’#view’).click(function() {
    var users = ”;
    $(’#selected_users .innertxt2′).each(function() {
    var user_id = $(this).attr(’userid’);
    if (users == ”)
    users += user_id;
    else
    users += ‘,’ + user_id;
    });
    $(“#users”).val(users);
    });

  3. #3 by Nour - April 23rd, 2009 at 18:31

    Hi Anil,
    When i validate the page i get this issue:
    Line 457, Column 57: Attribute “userid” is not a valid attribute. Did you mean “onmousedown” or “onmouseup”?

  4. #4 by Nour - April 23rd, 2009 at 20:54

    I mean when i try to validate the page with xhtml validator i get the error above.
    Do you have a good idea for this issue?

  5. #5 by admin - April 24th, 2009 at 12:53

    @ Nour

    Yes, there is the problem with attribute "userid" because its our custom attribute and not standard HTML attribute. But we can solve the validation problem by just doing some quick fixes.

    1. Change

    <div id="user1" userid="1" class="innertxt">

    to

    <div id="user1" class="innertxt">

    2. Change

    var user_id = $(this).attr(‘userid’);

    to

    var user_id = $(this).attr(‘id’).substring(4);

    in all the places.

  6. #6 by Nour - April 26th, 2009 at 03:04

    I could not fix it.

    I have used your script for these site,
    it is a great script i love it
    http://www.dynascript.nl/admin/article/add-article

    http://www.dynascript.nl/admin/article/edit-article/id/798

  7. #7 by admin - April 27th, 2009 at 11:07

    @ Nour
    Can you tell me in detail what error/issue you are facing in (XHTML validation). So, I can help you. I opened the links you provided above but I can’t see any implemention of this script. You can give me the exact URL where you implemented this script.

    Thanks,
    Anil

  8. #8 by jason - June 23rd, 2009 at 02:13

    Great script!

    I am trying to take it up and combine it with a live search that runs off of a mysql db back-end. I can load the data into “all_users” on page load and have it function without any problems, however when I re-populate the contents of “all_users” through the live-search results, the “innertxt_bg” class is not injected into the tag. It seems that using the DOM to manipulate the contents of the #all_users div works for the display but jQuery does not know about the changes – is there any call that needs to be made through jQuery to alert it that the contents of the page have been dynamically modified through AJAX?

    You can see what I’m talking about here…

    http://dev.mountainpinedesign.com/crew-call/

    If you’re using firefox you can easily see the dynamic content through firebug. Note that when the page loads, the class is being injected without problems. Once you type a letter or two into the search box, the page updates but breaks the list swap functionality…

    Any thoughts? Thanks so much in advance!

  9. #9 by admin - June 23rd, 2009 at 11:03

    @ jason
    Actually, we mapped the click event on “#all_users .selectit” and “#selected_users .selectit” at the time of page load. So, when you update the content of “#all_users” you need to map the click event again on the injected content. You can do it in after your AJAX call when data is inserted in the “#all_users”. Like this:

    /*Code*/
    function getResults() {
    $.get(“search.php”,{query: $(“#searchbox”).val(), type: “results”}, function(data)
    {
    $(“#all_users”).html(data);
    $(“#all_users”).show(“blind”);

    $(‘#all_users .selectit’).click(function() {
    var userid = $(this).val();
    $(‘#user’ + userid).toggleClass(‘innertxt_bg’);
    });
    });
    }

    Let me know if you still having any query.

  10. #10 by brion - June 24th, 2009 at 11:06

    hi nice tutorial and thanks,
    would it also be easy to save the list into a database? so even if you referesh or come back later its still there?

  11. #11 by admin - June 24th, 2009 at 12:29

    @brion
    Brion, Yes you can easily do this. You just need to save the selected IDs in your database and when you generate the page using your server side script (PHP, Perl, or any one) you just generate the HTML for already selected items (Saved in your Database) in "<div id=”selected_users”></div>" div exactly in same format which we have for "<div id=”all_users”></div>".
    So, when you come back or refresh the page you will get the saved list on right side. You can easily remove the selected items from your right list and save it again.
    -Anil

  12. #12 by brion - June 25th, 2009 at 03:33

    @ admin
    brilliant thanks

  13. #13 by brion - June 25th, 2009 at 05:46

    I tried to get it to auto save the settings + text into mysql using php using the ‘click’ function.
    Ive got a textbox included and i want to grab its text using getElementById as well as the userid and save in db.
    Its not liking it, any idea why?

    $(‘#view’).click(function() {
    var users = ”;
    $(‘#selected_users .innertxt2′).each(function() {
    var user_id = $(this).attr(‘userid’);

    if (users == ”)
    users += user_id;

    else
    users += ‘,’ +user_id;
    text+= document.getElementById(‘text’).value;
    });
    CODE HERE TO CONNECT TO PHP TO SEND TO DB
    });

  14. #14 by brion - June 25th, 2009 at 06:13

    actually on reading the comments, i think you already answered a sorta similar question in the top comment.

    ill try that. and get back.

    thanks

  15. #15 by admin - June 25th, 2009 at 12:42

    @brion
    Yes. You most welcome.

  16. #16 by Argg - August 2nd, 2009 at 11:00

    Thanks exactly what I was looking for

  17. #17 by Joe - June 11th, 2010 at 16:31

    Hello! I know that the last entry was about a year ago, but I’m hoping I could still get assistance. This is a great feature and I appreciate you sharing it with us.

    What I’ve done is replaced the hard-coded user divs with a single div that pulls data from my MySQL database. This single div is encapsulated with PHP echo statements. While I am able to populate the left-hand side with user 1-12 (for example), when I select a few users and click on the ‘Right’ hyperlink, nothing moves to the right-hand block. I have a hunch that it has something to do with the PHP executing at the initial page load and there is no way for the javascript to communicate back to the server side. I’m a newbie to programming so I apologize in advance for this general question. Thanks again.

  18. #18 by admin - June 12th, 2010 at 03:04

    @Joe
    Hi Joe,

    I think you missed something in PHP echo statement. Could you compare you PHP generated output with the hard-coded DIVs. They should match exactly. Here JavaScript execution start when the page load completely because we are using “$(document).ready()” so it will assign all the event handlers accordingly after page load.

  19. #19 by Joe - June 12th, 2010 at 09:32

    @ admin
    Thank you very much! I compared your original source with what I had. You were right. I overlooked something very simple:

    echo””;

    I left out the word “user” in my DIV ID attribute. So instead of seeing “div id=user1, user 2, etc.”, I was getting “div id=1, 2, etc.” which doesn’t exist. Thanks again!

  20. #20 by Joe - June 15th, 2010 at 08:00

    Hi again!

    I just wanted to run an idea by you. Is it possible to apply cascading combo boxes to filter out a certain group of users listed in the left-hand DIV (“All Users”)?

    For example, if I have a database of users, and wish to filter out users based on select criteria, could the “All Users” column only show the results that apply to the filter? Thanks!

  21. #21 by Joe - July 3rd, 2010 at 15:52

    @ admin
    Hello ‘Admin’,

    To supplement my question in #20, I’ve added the following URL to my site showing the example of what I’m trying to do:

    http://www.st-dev.herobo.com/html/shopping_list.php

    Any comments, feedback, or hints would be greatly appreciated. Thanks!

  22. #22 by admin - July 5th, 2010 at 01:38

    @Joe
    You can update the content of left DIV dynamically on the basis of selected combo box values. You can send the AJAX request to you server with selected values and return response either in HTML or in JSON string. In case of HTML you can directly inject the content in left DIV using innerHTML. For JSON you have to create DOM elements using JavaScript using JSON response. But the important thing is after updating the content in left DIV you have to re-assign/map all the events again for new content of left DIV. Otherwise the items from left list will not move to right list.

    Basically you have to call this code whenever you update/change the content in left list.

    $(’#all_users .selectit’).click(function() {
    var userid = $(this).val();
    $(’#user’ + userid).toggleClass(’innertxt_bg’);
    });

  23. #23 by Joe - July 5th, 2010 at 16:11

    @ admin
    Thanks again! I will play around with it and keep you posted.

  24. #24 by Praful Rajput - January 1st, 2011 at 22:59

    Really Thanks a lot…
    i was searching it from long days!!!!!!!!!

    I found perfect here only..

    but i need to shown data from table and
    stored selected data in table..

    If possible then plz send something like this

  25. #25 by Twitch - January 12th, 2011 at 19:37

    Hi Anil,

    I love this script I was hoping to use it but it seems I have the issue where the checked users on the left won’t go to the right after dynamically generating the list. I saw you posted code that needs to be called whenever the list is generated but I wasn’t sure how and where to call it.

    This is the code I use to generated the list:

    $(‘#search_types’).live(‘change’, function() {
    var chosenType = $(‘#search_types’).val();
    var getProducts = ‘id=’+ chosenType;//used for POST
    $.ajax({
    type: “POST”,
    url: “products_by_type.php”,//get product info
    data: getProducts,
    cache: false,

    success: function(html){
    $(‘#all_users’).html(html);//set the product menu of the new clone to show all products
    /*I ASSUME IT WOULD BE CALLED HERE, BUT EVERYTHING I TRIED FAILED*/

    }//end success
    });//end ajax
    });

    Thank you in advance,
    Twitch

  26. #26 by admin - January 13th, 2011 at 14:13

    @Twitch
    Yes you picked the spot correctly. You need to call

    $(‘#all_users .selectit’).click(function() {
    var userid = $(this).val();
    $(‘#user’ + userid).toggleClass(‘innertxt_bg’);
    });

    lines after assigning the response html in #all_users DIV. Could you make sure your response have the correct html which required in #all_users DIV. I mean you need to verify all IDs and Classes assigned properly and in correct parent-child relationship.

  27. #27 by Twitch - January 13th, 2011 at 19:32

    Thanks for the reply. Really appreciate it. I will give it a try.

    Awesome script.

  28. #28 by nirmala - March 29th, 2011 at 12:13

    it’s working have some problem for maintain client status .i wish to refresh a left div only while i close my new window .how’s tat?

  29. #29 by Jhonny - April 17th, 2011 at 04:33

    Hi, I think your script is great, but I can’t still use it correctly. I use ajax to generate the elements on the list, everything works, except when I try to take an element from left to right.

    I read your answer to Twitch and try to use that, but still don’t get results.

    Here is my code:

    $(document).ready(function () {
    $.ajax({
    type: “GET”,
    url: ”,
    dataType: “xml”, // I use xml
    success: function(xml){
    var cadena=””;
    $(xml).find(“alumno”).each(function () {
    cadena=cadena+’\n\
    ‘+$(this).find(“nombre”).text()+’\n\
    \n\
    \n\
      Select it.';
    });
    $(‘#all_users’).html(cadena);
    $(‘#all_users .selectit’).click(function() {
    var userid = $(this).val();

    $(‘#user’ + userid).toggleClass(‘innertxt_bg’);
    });
    $(‘#selected_users .selectit’).click(function() {
    var userid = $(this).val();
    $(‘#user’ + userid).toggleClass(‘innertxt_bg’);
    });
    // asignarAcciones();

    }

    });

    colocarOpciones(); // I call hear to the other functions
    });
    }

    Thanks

    Jhonny, from Ecuador

  30. #30 by Hina - April 26th, 2011 at 13:07

    Please help me ..Its not throwing any error but data still not move to second list ..I just debug this and got to know this function is not callin ..do u know why?
    $(‘#all_users .innertxt_bg’).each(function() {

  31. #31 by Andreea - June 13th, 2011 at 19:35

    Hi Anil!
    I looked at your code and it is wonderful but I was wondering how could it be modified to just copy the elements from one list to another. If you delete the part where the elements in the old list get removed then you will have two elements with the same attributes and so on and everything goes wrong afterwards. Do you have any idea on how to do it?
    Thanks!

  32. #32 by David Buckley - September 19th, 2011 at 19:50

    I am using your script for a client category selection for his web site however How would I go about saving the values in the selected list to database using php where in your code would i need to put in the jquery code

    php and mysql

    Thanks
    David

  33. #33 by admin - September 20th, 2011 at 10:12

    @David Buckley
    Hi David,

    To save selected categories in DB you need to send the ID’s of selected categories to server using AJAX. You can use jQuery for you AJAX implementation. You need to modify the function called on click of “View” button. Here is the updated code snippet:

    $(‘#view’).click(function() {
    var users = “;

    $(‘#selected_users .innertxt2′).each(function() {
    var user_id = $(this).attr(‘userid’);
    if (users == “)
    users += user_id;
    else
    users += ‘,’ + user_id;
    });

    if (users == ”) {
    alert(‘Select category’);
    return;
    }

    jQuery.ajax({
    url:’php_file.php’,
    data:{‘selected_cids': users},
    type:’POST’,
    success:function(info) {
    alert(‘Data has been save successfully in DB.’);
    }
    });
    });

    You can retrieve the selected category ID’s at server side using $_POST[‘selected_cids’].

  34. #34 by sumit - September 30th, 2011 at 17:35

    I am trying to use this script. I am assigning a hidden input field to the div..
    When i inspect the elements..it see the div that I have moved is actually ..I am not getting how to get the values from the input elements in #view..
    –My code—

    All Users

    User ID: 1
      Select it.

    User ID: 2
      Select it.

    User ID: 3
      Select it.

    User ID: 4
      Select it.

    User ID: 5
      Select it.

    User ID: 6
      Select it.

    User ID: 7
      Select it.

    Right »
    « Left

    Select maximum 5.

  35. #35 by sumit - September 30th, 2011 at 17:37

    I just added “” in all tag

  36. #36 by Mark - October 5th, 2011 at 14:29

    This is a great script. How could i change it to this scenario?

    I have a table of games in a grid, say 4 x 4. I want to drag any one of the td elements to another and invoke a function with the id numbers of each div, the source and the target.

    I plan to make each table td contain a div with an id for the game.

  37. #37 by Viktor - November 11th, 2011 at 15:08

    Hello, thank you very much for the wonderful script.
    I have a question! Can I do so that would be chosen by users who have already been recorded in the database have already been allocated in the right box?

Comments are closed.