摘要: jQuery - 使用 jQuery 簡單做資料左右增減
最近因為專案的需求,利用 jQuery 實做了一個資料佐又增刪的功能,我想這樣說應該滿多人不知道我在說啥,當你看到下面的實作,相信你會知道在做甚麼...
目標:以下就以 ASP.NET MVC 來實作
步驟一:加入 AdventureWorks 中的 Product 資料表
步驟二:CS 中的程式碼
01
public ActionResult demoExample()
02
{
03
public ActionResult demoExample()
04
{
05
using (MyDataContext db = new MyDataContext())
06
{
07
var result = from p in db.Product
08
orderby p.Name
09
select new SelectListItem
10
{
11
Text = p.Name,
12
Value = Convert.ToString(p.ProductID)
13
};
14
15
ViewData["ProductList"] = result.Take(10).ToList();
16
}
17
18
return View();
19
}

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

步驟三:在 HTML 的程式碼
01 <table border=0>
02 <tr>
03 <td><%=Html.ListBox("ProductList", ViewData["ProductList"] as IEnumerable<SelectListItem>, new { style = "width:200px; height:400px;" })%></td>
04 <td>
05 <table border=0>
06 <tr>
07 <td><input type="button" id="btnRight" name="btnRight" value=">>" /></td>
08 </tr>
09 <tr>
10 <td><input type="button" id="btnLeft" name="btnLeft" value="<<" /></td>
11 </tr>
12 </table>
13 </td>
14 <td><select id = "ChooseProduct" multiple="multiple" style = "width:200px; height:400px;"></select></td>
15 </tr>
16 </table>
02 <tr>
03 <td><%=Html.ListBox("ProductList", ViewData["ProductList"] as IEnumerable<SelectListItem>, new { style = "width:200px; height:400px;" })%></td>
04 <td>
05 <table border=0>
06 <tr>
07 <td><input type="button" id="btnRight" name="btnRight" value=">>" /></td>
08 </tr>
09 <tr>
10 <td><input type="button" id="btnLeft" name="btnLeft" value="<<" /></td>
11 </tr>
12 </table>
13 </td>
14 <td><select id = "ChooseProduct" multiple="multiple" style = "width:200px; height:400px;"></select></td>
15 </tr>
16 </table>
步驟四:jQuery 的程式碼
01
<script type="text/javascript">
02
03
$('#btnRight').click(function() {
04
$('#ProductList option:selected').each(function() {
05
$("#ChooseProduct").append("<option value='" + $(this).val() + "'>" + $(this).text() + "</option>");
06
$(this).remove();
07
});
08
});
09
10
$('#btnLeft').click(function() {
11
$('#ChooseProduct option:selected').each(function() {
12
$("#ProductList").append("<option value='" + $(this).val() + "'>" + $(this).text() + "</option>");
13
$(this).remove();
14
});
15
});
16
17
</script>

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17
