JS component BootstrapTable table implement code _ javascript

Source: Internet
Author: User
This article mainly introduces the implementation code of the multi-row drag-and-drop effect of the JS component BootstrapTable Table. For more information, see <G id = "1"> drag-and-drop of the JS component Bootstrap Table </G>, to meet the new requirements, you need to drag and drop selected rows at the same time on the basis of the previous table row dragging. It took me half a day to study the effect, but it was unsatisfactory. Share it first, and think of a better way to optimize it later.

I. effect display

1. Before dragging

2. Dragging

3. After dragging

4. Undo it back to the status before dragging

Ii. Demand Analysis
Through the previous article, we know that to implement drag and drop, there must be a label that can be dragged, or a container. For example, tr in the previous article is a drag container, if you want to drag the selected row, the first response of the blogger is to put the selected row in a container, for example, put it in a p, and then register the p to be dragged, however, the actual situation is that tr is a label in the table. If tr is packaged with p, the style in the table will be disrupted, and the interface will be broken. Obviously, this road cannot be achieved. Then, we can use Google's browser to review the elements and find that the parent element of the table tr generated using Bootstrap table is actually tbody, so we are wondering if we can register the tbody drag. This method is feasible. So let's get started.

Iii. Sample Code
The Code of cshtm is no longer repeated. Let's focus on the js Code.

Var I _statuindex = 0; var arrdata = []; var m_oTable = null; $ (function () {// 1. initialize the table m_oTable = new TableInit (); m_oTable.Init (); // 2. initialization button event var oButtonInit = new ButtonInit (); oButtonInit. init (); // 3. date control initialization $ (". 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. ini T = 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. queryParams, queryParamsType: "limit", sidePagination: "server", pageSize: 10, pageList: [10, 25, 50,100], search: true, strictSearch: true, showColumns: true, showRefresh: true, m InimumCountColumns: 2, clickToSelect: true, columns: [{checkbox: true}, {field: 'order _ no', title: 'order number'}, {field: 'Body _ no', title: 'body'}, {field: 'vin ', title: 'vin Code'}, {field: 'Tm _ MODEL_MATERIAL_ID', title: '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 launch date '},{ Field: 'vms _ no', title: 'vms NO. '}, {field: 'Engin _ Code', title: 'Engine NO.'}, {field: 'Trans _ Code', title: 'gearbox No. '}, {field: 'offline _ DATE_ACT', title: 'actual deprecation date'}, {field: 'Hold _ res', title: 'hold justification '}, {field: 'spc _ FLAG', title: 'Special tag'},], onLoadSuccess: function (data) {oTableInit. initDrag (); if (data. total> 0) {var iheight = $ ('# p_tableleft '). find (". fixed-table-container "). height (); $ ('# p _ 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, striped: true, pagi Nation: true, height: 600, queryParams: oTableInit. queryParamsRight, queryParamsType: "limit", // ajaxOptions: {departmentname: "", statu: ""}, sidePagination: "server", pageSize: 10, pageList: [10, 25, 50,100], search: true, strictSearch: true, showRefresh: true, minimumCountColumns: 2, columns: [{field: 'order _ no', title: 'order NO '}, {field: 'body _ no', title: 'body'}, {field: 'vin ', title: 'v IN code '}, {field: 'Tm _ MODEL_MATERIAL_ID', title: '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 launch date'}, {field: 'vms _ no', title: 'vms NO. '}, {field: 'Engin _ Code', title: 'Engine No. '}, {field: 'Trans _ Code', title: 'gearbox No.'}, {field: 'offline _ DATE_ACT ', title: 'actual deprecation date'}, {field :' HOLD_RES ', title: 'hold justification'}, {field: 'spc _ FLAG ', title: 'Special tag'},], onLoadSuccess: function (data) {oTableInit. initDrop () ;}}) ;}; 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 '). boo TstrapTable ("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 () {$ ("# p_tableright p [class = fixed-table-container]"). droppable ({drop: function (event, ui) {var arrtr =$ (ui. helper [0]). find ("tr [class = selected]"); if (arrtr. length <= 0) {alert ("Please select first Insert a single row "); 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) {// configure the parameter var temp = {// The name of the key and the variable name of the controller must be the same. If this parameter is changed, the Controller also needs Change to the same limit: params. limit, // page size offset: params. offset, // page 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 (), strIm PortStartdate: $ ("# 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) {// configure the parameter var temp = {// The Name Of The key here and the variable name of the controller must be consistent. Here we change it, the Controller also needs to be changed to the same limit: params. limit, // page size offset: params. offset, // Page number strBodyno: "", strVin: "", strOrderno: "", strEngincode: "", strOrderstatus: 5, strTranscode: "", strVms: "", strCarcode: "", strImportStartdate: "", 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 "). c Lick (function () {$ ("# tb_order_left "). bootstrapTable ('refresh') ;}); // reset the Click Event $ ("# btn_reset "). click (function () {$ (". container-fluid "). find (". form-control "). val (""); $ ("# tb_order_left "). bootstrapTable ('refresh') ;}); // click an event in the insert ticket operation $ ("# btn_insertorder "). click (function () {}); // click event to undo the 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; x ++) {$ ("# tb_order_right "). bootstrapTable ("insertRow", {index: x, row: arr_right_data [x]});} // $ ('# tb_order_right '). bootstrapTable ('append', arr_right_data); // After append, you cannot drop break;} I _statuindex --; // you can drag m_oTable.InitDrag () to re-register (); // m_oTable.InitDrop () ;}; return oInit ;};

Focus on some code

1. Drag To the left of Registration

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


The code here is very simple and mainly involves two things:

(1) register the draggable event of the tbody, which is also applicable to the JQuery UI.

(2) Save the data of tables on both sides before you start to drag and drop to restore the data.

2. register the right-side drop

$ ("# P_tableright p [class = fixed-table-container]"). droppable ({drop: function (event, ui) {var arrtr =$ (ui. helper [0]). find ("tr [class = selected]"); if (arrtr. length <= 0) {alert ("select the row 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-I RowHeadHeight)/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 ();}});


The code here is somewhat different from the previous one.

(1) register the droppable of the # p_tableright p [class = fixed-table-container] label, which is automatically generated after the Bootstrap Table table is initialized, why not register the droppable of table # tb_order_right directly? Because the label scope is too small, the tbody dragged by the label cannot capture the drop event. Register the p tag of # p_tableright p [class = fixed-table-container] outside the table to solve the problem.

(2) use var arrtr =$ (ui. helper [0]). find ("tr [class = selected]"); find the row selected in the tbody, insert the data into the right table, and delete the row data in the left table.

(3) The trouble here is to find the drop location. We know that to place the row selected on the left to the position specified on the right, we need to get the current mouse drop location, the ui is used here. helper [0]. the offsetTop attribute is used to obtain the y-axis position of the mouse, and the position to be inserted is calculated.

3. Cancel the 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; x ++) {$ ("# tb_order_right "). bootstrapTable ("insertRow", {index: x, row: arr_right_data [x]});} // $ ('# tb_order_right '). bootstrapTable ('append', arr_right_data); // you cannot drop break after append;} I _statuindex --; // you can drag m_oTable.InitDrag (); // m_oTable.InitDrop ();});

The Undo operation is basically the same as before.

Iv. Summary
The result is finished. The disadvantage is that the entire tbody is dragged every time, instead of the selected row. Instead, multiple selected rows cannot be wrapped in a container. No suitable solution is found. Let's do this first. Wait for a good solution to be optimized.

V. optimization solution

1. drap Registration 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 (); in this way, the unselected row is invisible during the drag operation.
2. accurately locate the specified position in the right table:

OTableInit. initDrop = function () {$ ("# p_tableright p [class = fixed-table-container]"). droppable ({drop: function (event, ui) {var arrtr =$ (ui. helper [0]). find ("tr [class = selected]"); if (arrtr. length <= 0) {toastr. warning ('select the row to be inserted First '); return;} var oTop = ui. helper [0]. offsetTop; // because the height of each row in the table may be inconsistent, the method for getting the inserted row location here is to accumulate the Row Height of the table on the right and 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 situation of dragging to the bottom of the right table, in this case, this condition is not entered. 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 rows in each row are highly uncertain and are dynamically supported by the data in the row, the drop position is also dynamically calculated here.

So far, this small feature has come to an end, and the basic effects and points to be optimized have also been completed.

Download source code:Bootstrap Table multi-row dragging

The above is all the 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.