Search This Blog

Thursday, October 18, 2012

Move elements from one list to another using jquery

This post will not help the C# gurus. Because they are already using this feature different techniques. But I hope this will be helpful for the PHP beginners :) . Now I am going to show you how you can move list items from one list box to another using simple jquery. Using jquery it is very simple than you think. :)

This is the Jquery portion:

 <script src="jquery-1.6.2.js"></script>

 <script>

 function move_forward()

 {

     //taking the selected items of list 1 and concatenating to a variable named forward_variable.

   var forward_variable='';

   $("#list1 :selected").each(function(){

       forward_variable+="<option value='"+$(this).val()+"'>"+$(this).html()+"</option>";

       $(this).remove();  

   });

     //Now appending the selected firs list's element to the list 2.

   $("#list2").append(forward_variable);

     //Sorting the list 2 so that it shows the list alphabetically

   sort_element("list2");

 }

 function move_backward()

 {

   var backward_variable='';

     //taking the selected items of list 2 and concatenating to a variable named backward_variable.

   $("#list2 :selected").each(function(){

       backward_variable+="<option value='"+$(this).val()+"'>"+$(this).html()+"</option>";

       $(this).remove();  

   });

    //Now appending the selected firs list's element to the list 1.

   $("#list1").append(backward_variable);

     //Sorting the list 2 so that it shows the list alphabetically

   sort_element("list1");

 }

 //Sorting function to sort the elements

 function sort_element(id)

 {

   var select_element = $('#'+id);

   var options_element = select_element.children('option').get();

   options_element.sort(function(a, b) {

     var compA = $(a).text().toUpperCase();

     var compB = $(b).text().toUpperCase();

     return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;

   })

   $.each(options_element, function(index, items) { select_element.append(items); });

 }

 </script>


Now comes the html portion.
 <select multiple="multiple" name="list1" id="list1" style="width:200px">

   <option value="1">Ecstasy</option>  

   <option value="2">Tanjim</option>

   <option value="3">Rex</option>

   <option value="4">Artisti</option>

   <option value="5">Infinity</option>

 </select>

 <input type="button" name="forward" id="forward" onclick="move_forward()" value=">>"/>

 <input type="button" name="backward" id="backward" onclick="move_backward()" value="<<"/>

 <select multiple="multiple" name="list2" id="list2" style="width:200px">

 </select>



Simple is not it? Copy and paste the code. Run..

No comments:

Post a Comment