Introduction

This article explains how to move data from one ListBox to another ListBox using jQuery. Here we create two ListBoxes in which one has the list of cities, when we select the data from the ListBox and click on the "LeftShift" button then it moves the data to the second ListBox. In the same way we move the data from the second ListBox to the first ListBox. For this operation we need to use jQuery.

Use the following procedure to create the sample.

Step 1

Create a Web API application:

Step 2

Now in the "HomeController" add the code. This file exists:

Add the following code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace MovedataListBox.Controllers
  7. {
  8. [HandleError]
  9. public class HomeController : Controller
  10. {
  11. public ActionResult Index()
  12. {
  13. ViewData["Message"] = "Welcome";
  14. return View();
  15. }
  16. }
  17. }

Step 3

Add the following code:

  1. <html>
  2. <head>
  3. <title></title>
  4. <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
  5. <script type="text/javascript">
  6. $(function () {
  7. $("#ShiftRight,#ShiftLeft").click(function (event) {
  8. var ID = $(event.target).attr("ID");
  9. var ChooseFrom = ID == "ShiftRight" ? "#ChooseLeft" : "#ChooseRight";
  10. var moveTo = ID == "ShiftRight" ? "#ChooseRight" : "#ChooseLeft";
  11. var SelectData = $(ChooseFrom + " :selected").toArray();
  12. $(moveTo).append(SelectData);
  13. SelectData.remove;
  14. });
  15. });
  16. </script>
  17. </head>
  18. <body>
  19. <form method="get">
  20. <select id="ChooseLeft" multiple="multiple">
  21. <option value="1">Lucknow</option>
  22. <option value="2">Kanpur</option>
  23. <option value="3">Delhi</option>
  24. <option value="4">Gurgao</option>
  25. <option value="5">Noida</option>
  26. <option value="5">Agra</option>
  27. <option value="5">Banglore</option>
  28. <option value="5">Rajasthan</option>
  29. <option value="5">Pune</option>
  30. </select>
  31. <input id="ShiftRight" type="button" value=" ShftRight (>>) " />
  32. <input id="ShiftLeft" type="button" value="ShiftLeft(<<) " />
  33. <select id="ChooseRight" multiple="multiple">
  34. </select>
  35. </form>
  36. </body>
  37. </html>

Step 4

Execute the application:

View List

Select the data from the list and click on the "RightShift" button. We can move more than one data from one list to another list.

Move one item:

Move One item to list

Move two items:

Move two items

Now the same as selecting data from the right list box and click on the "LeftShift" button.

Move items Right to Left