JS Component Bootstrap table table multi-row Drag effect to achieve code _JAVASCRIPT skills

Source: Internet
Author: User

Preface: The day before yesterday just wrote a JS component bootstrap table table row Drag effect, today received new needs, need to be in the table row dragged on the basis of the can drag and drop the selected multiline. After a half-day study, the effect is out, but the feeling is not satisfactory. Share it first and think of a better way to optimize it later.

One, the effect shows

1, before dragging

2, drag in

3, after dragging

4, undo back to drag before the state

Second, demand analysis
As we know from the previous article, if you want to implement drag and drop, you have to have a tag that you can drag, or a container, for example, the TR in the previous article is a drag-and-drop container, so if you want to implement the drag of the selected row, the first response of the blogger is to put the selected row into a container, such as a Div, And then register this div can be dragged, but the reality is, TR is in the table inside the label, if the TR with Div wrapped up, will be the table inside the style upset, this interface is really disorderly off. It is obvious that the road is out of line. Then through the Google Browser audit elements know that the table generated with bootstrap tables TR's parent element is actually tbody, so in the thought of whether can register tbody drag, practice has proved that this method is feasible. So I started to do this.

Third, code example
The cshtm code is no longer repeated, as in the previous article. Let's look at the JS code.

var i_statuindex = 0;

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 () {$ (' #tb_order_left '). bootstraptable ({url: '/api/orderapi/get ', method: ' Get ', striped: True, Cache:false, Striped:true, Pagination:true, height:600, uniqueId: "to_order_id", queryparams:otableinit.q Ueryparams, Queryparamstype: "Limit", Sidepagination: "Server", Pagesize:10, PageList: [A, M, MB], search:tr UE, Strictsearch:true, Showcolumns:true, Showrefresh:true, Minimumcountcolumns:2, clicktoselect:true, columns: [{checkbox:true}, {field: ' Order_no ', title: ' Order Number '}, {field: ' Body_no ', title: ' BodyNumber '}, {field: ' Vin ', title: ' Vin Code '}, {field: ' tm_model_material_id ', title: ' Full Vehicle 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 '}, {field: ' Hold_res ', titl
 E: ' Hold Reason '}, {field: ' Spc_flag ', title: ' Special Mark '},], onloadsuccess:function (data) {Otableinit.initdrag ();
 if (Data.total > 0) {var iheight = $ (' #div_tableleft '). Find (". Fixed-table-container"). Height ();
 $ (' #div_tableleft '). Find (". Fixed-table-container"). Height (iheight + 36);
 }, Oncheckall:function (rows) {$ ("#tb_order_left tbody tr"). AddClass ("selected");
 }, Onuncheckall:function (rows) {$ ("#tb_order_left tbody tr"). Removeclass ("selected");

 }
 }); $ (' #tb_order_right '). BooTstraptable ({url: '/api/orderapi/get ', method: ' Get ', toolbar: ' #toolbar_right ', striped:true, Cache:false, strip Ed:true, Pagination:true, height:600, QueryParams:oTableInit.queryParamsRight, Queryparamstype: "Limit",//AJAXOP  tions: {departmentname: "", Statu: ""}, Sidepagination: "Server", Pagesize:10, PageList: [A, N, M], search:
 True, Strictsearch:true, Showrefresh: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 vehicle Code '}, {field: ' Order_type ', title: ' Order type '}, {field: ' Order_status ', title: ' Order Status '}, {field: ' Create_da TE ', 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 Line Date '}, {field: ' HOLD_res ', title: ' Hold Reason '}, {field: ' Spc_flag ', title: ' Special Mark '},], onloadsuccess:function (data) {OTABLEINIT.I
 Nitdrop ();
 }
 });

 }; Otableinit.initdrag = function () {$ (' #tb_order_left tbody '). 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) {}});

 }; Otableinit.initdrop = function () {$ ("#div_tableright Div[class=fixed-table-container]"). Droppable ({drop:function (E
 Vent, UI) {var arrtr = $ (ui.helper[0]). Find ("tr[class=selected");
 if (arrtr.length <= 0) {alert ("Select the line to be inserted first");
 Return
 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);
 for (var i = 0; i < arrtr.length i++) {var ARRTD = $ (arrtr[i]). FIND ("TD");
 var UniqueID = $ (Arrtr[i]). attr ("Data-uniqueid"); 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:uniqueid};
 $ ("#tb_order_right"). Bootstraptable ("InsertRow", {index:rowindex++, row:rowdata}); $ (' #tb_order_left '). Bootstraptable ("Removebyuniqueid", 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 (), Strcarcode: $ ("#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,//Strbodyno page: "", STRVIn: "", Strorderno: "", Strengincode: "", Strorderstatus:5, Strtranscode: "", Strvms: "", Strcarcode: ", Strimpor
 Tstartdate: "", Strimportenddate: "", Strsendstartdate: "", 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 ');

 });

 Insert Single Action Click event $ ("#btn_insertorder"). Click (function () {});
 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:ar
 R_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 ();
 });

 };
return oinit;
 };

Let's focus on some of the code.

1, registered left can be dragged and dragged

$ (' #tb_order_left tbody '). 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) {
 }
 });


Here the code is very simple, mainly doing two things:

(1) Register the Draggable event of the Tbody, which is also applicable to the jquery UI.

(2) To save the data on both sides of the table before starting to drag and drop, for the restore operation.

2. Register right Drop

    $ ("#div_tableright Div[class=fixed-table-container]"). Droppable ({drop:function (event, UI) {var arrtr = $ (Ui.hel
 Per[0]). Find ("tr[class=selected]");
 if (arrtr.length <= 0) {alert ("Select the line to be inserted first");
 Return
 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);
 for (var i = 0; i < arrtr.length i++) {var ARRTD = $ (arrtr[i]). FIND ("TD");
 var UniqueID = $ (Arrtr[i]). attr ("Data-uniqueid"); 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:uniqueid};
 $ ("#tb_order_right"). Bootstraptable ("InsertRow", {index:rowindex++, row:rowdata});
 $ (' #tb_order_left '). Bootstraptable ("Removebyuniqueid", UniqueID);
 } Otableinit.initdrag ();
 }
 });


Here the code and a little change before

(1) Register the droppable of the #div_tableright Div[class=fixed-table-container] label, which is automatically generated when the bootstrap table is initialized, why not register the form directly #tb_ Order_right is droppable because the label scope is too small to cause the drop event to be caught by the tbody that is dragged over. The #div_tableright Div[class=fixed-table-container] on the outside of the registration form is the DIV tag that solves the problem.

(2) via var ARRTR = $ (ui.helper[0]). Find ("tr[class=selected]"); Locate the row that is selected in the Tbody, and then remove the data by inserting it in the right table and then the table on the left to delete the row data in turn.

(3) Here is a bit of trouble is to find the location of the drop, we know, to the left of the selected row to the right position, then you have to get the position of the current mouse drop, here through the Ui.helper[0].offsettop property to get the y-axis position of the mouse, Calculates the position to be inserted.

3. Undo Operation

$ ("#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 can drag
 M_otable.initdrag ();
 M_otable.initdrop ();
 });

Undo operations are basically the same as before.

Iv. Summary
The effect is completed, the drawback is that each dragged past is the entire tbody, rather than the selected line, but the number of selected lines can not be wrapped with a container. No suitable solution has been found for the time being. First of all, and then think of a good plan to optimize it.

V. Optimization scheme

1, registration of Drap method

Otableinit.initdrag = function () {
 $ (' #tb_order_left tbody '). 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);
 $ (ui.helper[0]). Find ("tr[class!=selected]"). Remove ();
 },
 Stop:function (event, UI) {
 }}
 );
 

Added this sentence $ (ui.helper[0]). Find ("tr[class!=selected]"). Remove (); When you drag, you can't see the unchecked row.
2, accurate positioning to the right table designated location:

Otableinit.initdrop = function () {$ ("#div_tableright Div[class=fixed-table-container]"). Droppable ({drop:function (E
 Vent, UI) {var arrtr = $ (ui.helper[0]). Find ("tr[class=selected");
 if (arrtr.length <= 0) {toastr.warning (' Please select the line to be inserted first ');
 Return
 var otop = ui.helper[0].offsettop;
 Because the height of each row in the table may not be the same, the way to insert the row is to add the row height of the table on the right to calculate the row index.
 var rowIndex = 0;
 var bisbottom = true;
 var irowheadheight = 40;
 var addheight = irowheadheight;
 var TRS = $ ("#tb_order_right tbody tr");
 for (var i = 0; i < trs.length i++) {addheight + = $ (trs[i]). Height ();
 if (Addheight > Otop) {rowIndex = i;
 Bisbottom = false;//Here The parameter is used to define the bottom of the table dragged to the right, which is not entered into this condition.
 Break
 } if (bisbottom) {rowIndex = Trs.length;
 for (var i = 0; i < arrtr.length i++) {var ARRTD = $ (arrtr[i]). FIND ("TD");
 var UniqueID = $ (Arrtr[i]). attr ("Data-uniqueid"); 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_name: $ (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:uniqueid, order
 _status:0};
 $ ("#tb_order_right"). Bootstraptable ("InsertRow", {index:rowindex++, row:rowdata});
 $ (' #tb_order_left '). Bootstraptable ("Removebyuniqueid", UniqueID);

 } Otableinit.initdrag ();
 }
 });
 };

Because the row height of each row is indeterminate, it is dynamically supported by the data in the row, so the position of the drop is also calculated dynamically here.

At this point, this small function basically came to an end, the basic effect and to be optimized points are completed.

SOURCE Download:Bootstrap table Table Multi-row Drag effect

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 this article will help you learn JavaScript programming.

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.