JS Component Bootstrap Table table row Drag effect to implement code _javascript skills

Source: Internet
Author: User
Tags button type

First, the business needs and realize the effect

The project involves the order module, that day suddenly received a demand, said that the two different state of the order to achieve the effect of a single, page presentation is: About two table, the left table inside is the status of 1 orders, the right table inside is the status of 2 orders, Left table inside the row of data dragged to the right table to specify the position of the row, drag finished, the table on the left to reduce a row, the table on the right to add a row. In addition, undo operations (equivalent to CTRL + Z Operations) are required to return to the previous step. May describe will let everybody imitate the ambiguity, anyway has already realized, first comes to see the effect chart.

1, first look at the effect of dragging before

2, this is the effect of dragging the left table row data

3, drag a row to complete the results of the table data

4, the second, the third drag completed after the effect

5, the right table above undo action Click Effect

6, multiple Click Undo, the form back to the initial state

Second, code example
the first feeling of receiving a demand is that it should be found in the Bootstrap table API, after all, the power of open source is powerful, and perhaps there is a relevant example. After a look, unfortunately, Bootstrap table does not have the operation between the two tables. Think about it, but it's understandable, Bootstrap table is bound to a dynamic table data, and it focuses on the functions inside the table, such as the drag-and-drop ordering of the rows within the table (Reorder rows) has a good solution, for the special needs such as bloggers, it seems that they should be implemented.
1, requirements analysis
Since the decision to write their own, and began to analyze the requirements, it seems that the operation is more difficult to drag the effect, said the effect of drag and drop, the original use of Jsplumb when the use of too much, So I thought of the draggable.js and droppable.js in our magical jquery UI. Drag-and-drop problem solved, then there is a difficult point, that is, how to undo the operation? We know what ctrl+z means to restore, what is called restore? is to return to the previous step, if you want to be able to save the state of the previous step, when it comes to saving a step, the blogger knows what to do and needs a global variable JSON with three key-value pairs, the index of the current step, the data on the left table, and the table on the right. It doesn't seem too hard, so go on and start.
2, code example
2.1 cshtml page code

 

2.2 js code

var i_statuindex = 0;

This array is used to save the data for each step of the undo operation var arrdata = [];

var m_otable = null;
 $ (function () {//1. initialization table m_otable = new Tableinit ();

 M_otable.init ();
 2. Initialize button event var obuttoninit = new Buttoninit ();

 Obuttoninit.init ();

3. Initialization of the date control $ (". DateTimePicker"). DateTimePicker ({format: ' Yyyy-mm-dd hh:ii ', Autoclose:true, Todaybtn:true,});

});

 Table-related events and methods var tableinit = function () {var otableinit = new Object (); Otableinit.init = function () {//Initialize table $ (' #tb_order_left ') to the left. Bootstraptable ({url: '/api/orderapi/get ', Method: ' Get ', Striped:true, Cache:false, Striped:true, Pagination:true, height:600, uniqueId: "to_order_id", Queryparam S:otableinit.queryparams, Queryparamstype: "Limit", Sidepagination: "Server", Pagesize:10, PageList: [10, 25, 50, 10 0], Search:true, Strictsearch:true, Showcolumns:true, Showrefresh:true, Minimumcountcolumns:2, clicktoselect:t Rue, columns: [{checkbox:true}, {field: ' Order_no ', title: ' Order Number '}, {field: ' Body_no ', title: ' Body Number '}, {field: ' Vin ', title: ' Vin Code '}, {field: ' tm_model_material_id ', title: ' Whole Car Code '}, {field: ' Order_type ', title: ' Order type '}, {field: ' Order_status ', title: ' Order Status '}, {field: ' Create_date ', Title: ' Order Import Time '}, {field: ' Plan_date ', title: ' Order plan online Date '}, {field: ' Vms_no ', title: ' VMS '}, {field: ' Engin_code ', title: ' Engine Number '}, {field: ' Trans_code ', title: ' Gearbox number '}, {field: ' Offline_date_act ', title: ' Actual offline date Period '}, {field: ' Hold_res ', title: ' HOLD Reason '}, {field: ' Spc_flag ', title: ' Special Mark '},], onloadsuccess:function (data)
 {///The initialization of Drag Otableinit.initdrag () After the table loading is completed;
     }
 }); Initializes the right table $ (' #tb_order_right '). bootstraptable ({url: '/api/orderapi/get ', method: ' Get ', toolbar: ' #toolbar_right ', s
 Triped:true, Cache:false, Striped:true, Pagination:true, height:600, QueryParams:oTableInit.queryParamsRight, Queryparamstype: "Limit",//ajaxoptions: {departmentname: "", Statu: "" }, Sidepagination: "Server", Pagesize:10, PageList: [Ten, M, MB], search:true, Strictsearch:true, Showrefre Sh:true, Minimumcountcolumns:2, columns: [{field: ' Order_no ', title: ' Order Number '}, {field: ' Body_no ', title: ' Body number '}, {field: ' Vin ', title: ' Vin Code '}, {field: ' tm_model_material_id ', title: ' Whole Car Code '}, {field: ' Order_type ', t Itle: ' Order type '}, {field: ' Order_status ', title: ' Order Status '}, {field: ' Create_date ', title: ' Order Import Time '}, {field: '
 Plan_date ', title: ' Order plan online Date '}, {field: ' Vms_no ', title: ' VMS '}, {field: ' Engin_code ', title: ' Engine Number '}, { Field: ' Trans_code ', title: ' Gearbox number '}, {field: ' Offline_date_act ', title: ' Actual offline Date '}, {field: ' Hold_res ', title
 : ' Hold Reason '}, {field: ' Spc_flag ', title: ' Special Mark '},], onloadsuccess:function (data) {Otableinit.initdrop ();
 }
 });
 }; Draggable Event Otableinit.initdrag = function () {$ (' #tb_order_left tr ') for the registration table row. draggable ({helper: "clone", Start:fun Ction (Event,UI) {var old_left_data = json.stringify ($ (' #tb_order_left '). Bootstraptable ("GetData"));
 var old_right_data = json.stringify ($ (' #tb_order_right '). Bootstraptable ("GetData"));
 var OData = {index: ++i_statuindex, Left_data:old_left_data, right_data:old_right_data};
 Arrdata.push (OData);
 }, Stop:function (event, UI) {}});
 };
 Registers the droppable event Otableinit.initdrop = function () {$ ("#tb_order_right") for the right table. Droppable ({drop:function (event, UI) {
 var ARRTD = $ (ui.helper[0]). FIND ("TD"); var rowdata = {order_no: $ (arrtd[1]). Text (), Body_no: $ (arrtd[2]). Text (), VIN: $ (arrtd[3)). Text (), Tm_model_mater IAL_ID: $ (arrtd[4]). Text (), Order_type: $ (arrtd[5]). Text (), Order_status: $ (arrtd[6)). Text (), Create_date: $ (arrtd[7 ]. Text () = "-"? Null: $ (arrtd[7]). Text (), Plan_date: $ (arrtd[8]). Text () = "-"? Null: $ (arrtd[8]). Text (), Vms_no: $ (arrtd[9]). Text (), Engin_code: $ (arrtd[10]). Text (), Trans_code: $ (arrtd[11]). Tex T (), Offline_date_act: $ (arrtd[12]). Text() == "-" ? Null: $ (arrtd[12]). Text (), Hold_res: $ (arrtd[13]). Text (), Spc_flag: $ (arrtd[14)). Text (), to_order_id: $ (ui.helper[0
 ]. attr ("Data-uniqueid")};
 var otop = ui.helper[0].offsettop;
 var irowheadheight = 40;
 var irowheight = 37;
 var rowIndex = 0;
 if (otop <= irowheadheight + irowheight/2) {rowIndex = 0;
 else {RowIndex = Math.ceil (otop-irowheadheight)/irowheight);
 //Insert the right table at the specified location row data $ ("#tb_order_right"). Bootstraptable ("InsertRow", {index:rowindex, row:rowdata});
 $ (' #tb_order_left '). Bootstraptable ("Removebyuniqueid", $ (ui.helper[0)). attr ("Data-uniqueid"));
 Otableinit.initdrag ();
 }
 });

 }; Otableinit.queryparams = function (params) {//configuration parameter var temp = {//The name of the key here and the variable name of the controller must always, this side changes, the controller also needs to change to the same limit:params.li MIT,//Page size Offset:params.offset,//number Strbodyno: $ ("#txt_search_bodynumber"). Val (), Strvin: $ ("#txt_search_vinnumber "). Val (), Strorderno: $ (" #txt_search_ordernumber "). Val (), Strengincode: $ (" #txt_search_engin_code "). Val (), strorderstatus:0, Strtranscode: $ ("#txt_search_trans_code"). Val (), Strvms: $ ("#txt_search_vms"). Val (), Strca
 Rcode: $ ("#txt_search_carcode"). Val (), Strimportstartdate: $ ("#txt_search_import_startdate"). Val (),
 Strimportenddate: $ ("#txt_search_import_enddate"). Val (), Strsendstartdate: $ ("#txt_search_send_startdate"). Val (),
 Strsendenddate: $ ("#txt_search_send_enddate"). Val (),};
 return temp;

 }; Otableinit.queryparamsright = function (params) {//configuration parameter var temp = {//The name of the key here and the variable name of the controller must always, this side changes, the controller also needs to change to the same Limit:para Ms.limit,//Page size Offset:params.offset,//number Strbodyno: "", Strvin: "", Strorderno: "", Strengincode: ", Strorderst Atus:5, Strtranscode: "", Strvms: "", Strcarcode: "", Strimportstartdate: "", Strimportenddate: "", Strsendstartdat
 E: "", Strsendenddate: "",};
 return temp;

 };
return otableinit;

};
 Page button initialization event var buttoninit = function () {var oinit = new Object ();

 var postdata = {}; Oinit.init = function () {//Query Click event $ ("#btn_quEry "). Click (function () {$ (" #tb_order_left "). Bootstraptable (' refresh ');

 });
 Reset Click event $ ("#btn_reset"). Click (function () {$ (". Container-fluid"). Find (". Form-control"). Val ("");
 $ ("#tb_order_left"). Bootstraptable (' refresh ');
 });
 Undo Action Click event $ ("#btn_cancel"). Click (function () {if (i_statuindex <= 0) {return;
 for (var i = 0; i < arrdata.length i++) {if (Arrdata[i].index!= i_statuindex) {continue;
 var arr_left_data = eval (arrdata[i].left_data);

 var arr_right_data = eval (arrdata[i].right_data);
 $ (' #tb_order_left '). Bootstraptable (' RemoveAll ');
 $ (' #tb_order_right '). Bootstraptable (' RemoveAll ');
 $ (' #tb_order_left '). Bootstraptable (' append ', arr_left_data); for (var x = 0; x < Arr_right_data.length + +) {$ ("#tb_order_right"). Bootstraptable ("InsertRow", {index:x, row:a
 RR_RIGHT_DATA[X]});
 //$ (' #tb_order_right '). Bootstraptable (' append ', arr_right_data); After//append cannot drop break;

 } i_statuindex--;
 Re-registration can be dragged M_otable.initdrag (); M_otable.iniTdrop ();

 }); Search bar Expand Click event $ ("#span_collapse"). Click (function () {if ($ (this). Text () = "Close") {$ (this). html (' Expand <label class= ' GL
 Yphicon Glyphicon-menu-down "></label>");
 $ ("#div_more_search"). Collapse (' hide ');
 else {$ (this). html (' <label class= ' Glyphicon glyphicon-menu-up ');
 $ ("#div_more_search"). Collapse (' Show ')}});

 };
return oinit;

 };

Let's focus on the code for a few places:
2.2.1 The table row can be dragged after the left table load succeeds.

$ (' #tb_order_left tr '). Draggable ({
 helper: "Clone",
 Start:function (event, UI) {
 var old_left_data = Json.stringify ($ (' #tb_order_left '). Bootstraptable ("GetData"));
 var old_right_data = json.stringify ($ (' #tb_order_right '). Bootstraptable ("GetData"));
 var OData = {index: ++i_statuindex, Left_data:old_left_data, right_data:old_right_data};
 Arrdata.push (OData);
 },
 Stop:function (event, UI) {
 }
 });

In the Draggable start event, we save all the data in the left and right table before dragging to the arrdata variable, i_statuindex This global variable is used to record the index of the current step to undo the operation.
2.2.2 On the right table droppable event that registers the form after the load succeeds    

$ ("#tb_order_right"). Droppable ({drop:function (event, UI) {var ARRTD = $ (ui.helper[0)). Find ("TD"); var rowdata = {order_no: $ (arrtd[1]). Text (), Body_no: $ (arrtd[2]). Text (), VIN: $ (arrtd[3)). Text (), Tm_model_material_ ID: $ (arrtd[4]). Text (), Order_type: $ (arrtd[5]). Text (), Order_status: $ (arrtd[6]). Text (), Create_date: $ (arrtd[7]). Text () = = "-"? Null: $ (arrtd[7]). Text (), Plan_date: $ (arrtd[8]). Text () = "-"? Null: $ (arrtd[8]). Text (), Vms_no: $ (arrtd[9]). Text (), Engin_code: $ (arrtd[10]). Text (), Trans_code: $ (arrtd[11]). Text ( ), Offline_date_act: $ (arrtd[12]). Text () = "-"? Null: $ (arrtd[12]). Text (), Hold_res: $ (arrtd[13]). Text (), Spc_flag: $ (arrtd[14]). Text (), to_order_id: $ (ui.helper[0))
 . attr ("Data-uniqueid")};
 var otop = ui.helper[0].offsettop;
 var irowheadheight = 40;
 var irowheight = 37;
 var rowIndex = 0;
 if (otop <= irowheadheight + irowheight/2) {rowIndex = 0;
 else {RowIndex = Math.ceil (otop-irowheadheight)/irowheight); } $ ("#tB_order_right "). Bootstraptable (" InsertRow ", {index:rowindex, row:rowdata});
 $ (' #tb_order_left '). Bootstraptable ("Removebyuniqueid", $ (ui.helper[0)). attr ("Data-uniqueid"));
 Otableinit.initdrag ();

 }
 });

At the drop event, take the currently dragged row data, calculate where the current mouse is located, and insert the dragged row data at the right table at the specified position. Then delete the row data that is dragged over the left table.
2.2.3 Undo Operation Code 

Undo Action Click event
 $ ("#btn_cancel"). Click (function () {
 if (i_statuindex <= 0) {return
 ;
 }
 for (var i = 0; i < arrdata.length i++) {
 if (arrdata[i].index!= i_statuindex) {
 continue;
 }
 var arr_left_data = eval (arrdata[i].left_data);
 var arr_right_data = eval (arrdata[i].right_data);

 $ (' #tb_order_left '). Bootstraptable (' RemoveAll ');
 $ (' #tb_order_right '). Bootstraptable (' RemoveAll ');
 $ (' #tb_order_left '). Bootstraptable (' append ', arr_left_data);
 for (var x = 0; x < Arr_right_data.length + +) {
 $ ("#tb_order_right"). Bootstraptable ("InsertRow", {index:x, row : Arr_right_data[x]});
 $ (' #tb_order_right '). Bootstraptable (' append ', arr_right_data);//append can not drop the break after
 ;
 }
 i_statuindex--;

 Rewrite registration to drag
 M_otable.initdrag ();
 

The undo operation is mainly through the global variable Arrdata inside the index to determine which step, and then the current step according to the index to remove the left and right table data, and then insert the data into the two table, and then i_statuindex in descending order, until equal to zero, because the left table row data all rewritten loaded, So you need to re-register to drag and drop events. Is such a simple three steps can achieve the desired effect, is not very simple ~ ~

If you want to further study, you can click here to learn, and then attach two wonderful topics: Bootstrap Learning Tutorials Bootstrap Practical course

The above is the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.