Summary of the use of Bootstrap table _javascript skills

Source: Internet
Author: User
Tags locale

Some of the things in jquery to learn at once, to complement, after all, sometimes not used in this way is very useful, when using bootstrap table, select the node currently selected the value of the ID in the current rows there are a lot of data, But I only need the ID of this one value, this time the operation is very simple.

$.map (Data,function (item,index) {return XXX})

Summary of Use:

Put an array in a new way to assemble and return, unlike the original array.

Iterates through each element of the data array and forms a new element in the return calculation, which is placed in the returned array

var B = $.map ([55,1,2], function (Item,index)
{return 
{ 
"label": Item,
"value": Index 
}
});

Output is 55 0

2. My backstage, is uses the SPRINGMVC to write, during it is also encountered many problems, carries on the paging processing to use the off-line query, but, I use is execute () This method, the incoming session is the proxy class data, The following method can not be converted to cause errors, I also Baidu for a long time, finally found that the problem caused by

/**
* Get a executable instance of <literal>criteria</literal>,
* to actually run the query.
* * Public
Criteria Getexecutablecriteria (Sessions session) {
impl.setsession (sessionimplementor); C6/>return impl;
}
Return (Pagebean) gethibernatetemplate (). Executewithnativesession (New Hibernatecallback () {public
Object Doinhibernate (Session session) throws Hibernateexception {
criteria = Detachedcriteria.getexecutablecriteria (session);
............................
}

Backstage, I returned the data and format is not according to the format of the bootstrap a little different, anyway, is not the same

{
"Success": True,
"message": null,
"data": {
"pageSize": "", "
rows": [
{
"userName": " 333 ",
" usertype ": 333,
" password ":" 333 ",
" id ": One,
" Indexcode ":" 333 "
},
{
" UserName ":" 3 ",
" usertype ": 333,
" password ":" 333 ",
" id ": 5,
" Indexcode ":" 33333 "
}
...
],
"Total": "
totalpage": 2,
"page": 0, "
haspreviouspage": True,
" Hasnextpage ': True,
' lastpage ': false,
' FirstPage ': false
}
}

Mainly here I am using a unified return interface ActionResult, so that the more convenient writing format, unified back end

* *
Created by Jetwang on 2016/10/1.
* * Public
class ActionResult {
private Boolean success;
private String message;
Private Object data;
Public ActionResult () {
} public
ActionResult (Boolean success) {This
(success, NULL, NULL);
}
............
}

Let's look at the front end effect.

Front-end pages

<%@ include file= "./common/common.jsp"%>//What common bootstrapt, jquery, and the like are put in the process
<script src= "<%= Baseurl%>/libs/bootstrap-table/dist/bootstrap-table.js "type=" Text/javascript "></script>
< Script src= "<%=baseurl%>/libs/bootstrap-table/dist/bootstrap-table-locale-all.js" type= "Text/javascript" >
</script>
<link rel= "stylesheet" href= "<%=baseurl%>/libs/bootstrap-table/dist/ Bootstrap-table.css "type=" text/css ">
//This is the
<div class=" container ">
<table ID where the table is placed in the container = "Table"
data-url= "/cms/userinfo/userinfopage" >//used path, background request URL
</table>
</div>

Description of the more important JS code

JQuery (document). Ready (function () {
///Here you can use a variety of wizards, you can also use the SEAJS front-end modular tool to
place our JS code is good
});

The following configuration file and some overrides of the event, you can look at the document, or go to your own source
Here you can rewrite Oh ~ ~, EXTENTD for a new cover!

Bootstraptable.defaults = {classes: ' Table Table-hover ', locale:undefined, height:undefined, Undefinedtext: '-', SortN ame:undefined, SortOrder: ' ASC ', Sortstable:false, Striped:false, Columns: [[]], data: [], DataField: ' Rows ', Method: '
Get ', url:undefined, ajax:undefined, Cache:true, ContentType: ' Application/json;charset=utf-8 ', I've added a utf-8 here. DataType: ' JSON ', ajaxoptions: {}, Queryparams:function (params) {//This is the setting of the query parameters, I directly in the source code modified, do not like offetset I used the background is pageno.
This processing on the comparison to meet my requirements, in fact, can also be changed in the background, trouble!
return params; }, Queryparamstype: ' Limit ',//undefined (here is the criteria for selecting different queries based on different parameters) Responsehandler:function (res) {//Here I look at the source,
After the success of the AJAX request, the data can be released before the release of data processing, return what part of the data, such as my need for rectification!
return res; }, Pagination:false, Onlyinfopagination:false, sidepagination: ' Client ',//client or Server totalrows:0,//server SID e need to set pagenumber:1, Pagesize:10, pagelist: [Ten, M, MB], paginationhalign: ' Right ',//right, left Paginatio Nvalign: ' Bottom ',//bottom, top, both PaginationdetailhaliGN: ' Left ',//right, left Paginationpretext: ' ‹ ', Paginationnexttext: ' › ', Search:false, Searchonenterkey:false, StrictS Earch:false, Searchalign: ' Right ', Selectitemname: ' Btselectitem ', Showheader:true, Showfooter:false, Showcolumns:fal
SE, showpaginationswitch:false,//show the number of pages selected? Showrefresh:false, Showtoggle:false, buttonsalign: ' Right ', smartdisplay:true, Escape:false, minimumcountcolumns:1, I dfield:undefined, uniqueid:undefined, Cardview:false, Detailview:false, Detailformatter:function (index, row) {Retur
n '; }, Trimonsearch:true, Clicktoselect:false, Singleselect:false, toolbar:undefined, toolbaralign: ' Left ', CheckboxHeade R:true, Sortable:true, Silentsort:true, Maintainselected:false, searchtimeout:500, SearchText: ', iconsize:undefine D, Buttonsclass: ' Default ', Iconsprefix: ' Glyphicon ',//Glyphicon of FA (font awesome) icons: {paginationswitchdown: ' GL Yphicon-collapse-down Icon-chevron-down ', paginationswitchup: ' Glyphicon-collapse-up icon-chevron-uP ', refresh: ' Glyphicon-refresh icon-refresh ', toggle: ' Glyphicon-list-alt icon-list-alt ', columns: ' glyphicon-th
Icon-th ', Detailopen: ' Glyphicon-plus icon-plus ', detailclose: ' Glyphicon-minus icon-minus '}, CustomSearch: $.noop, Customsort: $.noop, rowstyle:function (row, index) {return {};}, Rowattributes:function (row, index) {return {};}, F Ooterstyle:function (row, index) {return {};}, Onall:function (name, args) {return false;}, Onclickcell:function (f Ield, value, row, $element) {return false;}, ondblclickcell:function (field, value, row, $element) {return false;}, O Nclickrow:function (item, $element) {return false;}, Ondblclickrow:function (item, $element) {return false;}, Onsort : function (name, order) {return false;}, Oncheck:function (row) {return false;}, Onuncheck:function (row) {return
False }, Oncheckall:function (rows) {return false; Onuncheckall:function (rows) {return false;}, Onchecksome:function ( Rows) {return false;}, OnuncHecksome:function (rows) {return false;}, onloadsuccess:function (data) {return false;}, Onloaderror:function (stat US) {return false;}, oncolumnswitch:function (field, checked) {return false;}, onpagechange:function (number, size) {return false;}, Onsearch:function (text) {return false;}, Ontoggle:function (CardView) {return false;}, Onprebody
: function (data) {return false;}, Onpostbody:function () {return false;}, Onpostheader:function () {return false;
}, Onexpandrow:function (index, row, $detail) {return false;}, Oncollapserow:function (index, row) {return false;}, Onrefreshoptions:function (Options) {return false;}, Onrefresh:function (params) {return false;}, onresetview:funct Ion () {return false;}};

Look at the above oneself also basically know how to go, write! In fact, I did not dare to play like this before, but in the course of the practice of the tutor taught me how to play, so I dare, I believe, I can play well these things!

function inittable () {$table. bootstraptable ({striped:true,//table display stripe pagination:true,//Start paging pagesize:15,//per page number of records displayed) Pagenumber:1,//Current page pagelist: [10, 15, 20, 25],//number of records selectable list Search:false,//Whether to enable query Showcolumns:true,//Show dropdown box check the column show to display Sortname,sortorder//Set for limit can get limit, offset, search, sort, order responsehandler:function (RES) {//Remote data loading before
Handler response data format, object contains parameters: we can process the returned data format//After Ajax we can do some processing of events here return res.data; }, Queryparamstype: "Undefined", queryparams:function queryparams (params) {//Set query parameter var param = {//Here is the time when Ajax sends a request to set some
Parameter params have what thing, oneself see the source code to know PageNo:params.pageNumber, pageSize:params.pageSize};
return param; The Onloadsuccess:function (data) {///load succeeds when alert ("Load succeeded" +data); Onloaderror:function () {///load Failed to execute layer.msg ("failed loading ", {time:1500, icon:2});}, Height:getheight (), columns: [{field: ' state ', checkbox:true, align: ' center ', valign: ' Middle '}, {title: ' id ', field: ' ID ', align: ' center ', valign: ' Middle '}, {field: ' UserName ', title: ' UserName ', SOR Table:true, Footerformatter:totalnameformatter, align: ' center '}, {field: ' Usertype ', title: ' Usertype ', Sortable:tru E, align: ' center '}, {field: ' Password ', title: ' Userpass ', sortable:true, align: ' Center '},{field: ' Indexcode ', titl E: ' Indexcode ', sortable:true, align: ' Center '},{field: ' Operate ', Title: ' Item operate ', align: ' center ', events:oper Ateevents, Formatter:operateformatter}]});

The Footerformatter and formatter above are the events that are handled for the display of the current column, as follows in the document

Formatter

The context (this) is the column Object. The cell formatter function, take three parameters:value:the field value. Row:the row record data. Index:the row index. 
Footerformatter: The context (this) is the 
column Object. The function, take one parameter: Data:array of all the 
data rows. The function should return a string with the text To show in the footer cell.

are displayed for processing of the current column

The following is an increase of two buttons in a cell

function Operateformatter (value, row, index) {return
[
' <a class=] like "href=" javascript:void (0) "title=" Like ">",
' <i class= ' Glyphicon glyphicon-heart ' ></i> ',
' </a> ',
' <a class= ' Remove "href=" javascript:void (0) "title=" Remove ">",
' <i class= ' Glyphicon glyphicon-remove ' ></i> ',
' </a> '
].join (');
}

You can also add an event to the process here

<%--{
title: ' Operations ',
field: ' id ',
align: ' center ',
formatter:function (value,row,index) {
var e = ' <a href= ' # "mce_href=" # "onclick=" edit (\ ' + row.id + ') "> Edit </a>;
var d = ' <a href= ' # "mce_href=" # "onclick=" del (\ "+ row.id + ' \") "> Delete </a>";
return e+d;
You can also handle the event's
}
}--%>

The official Chinese file says the handling event can be handled as follows

The cell events listener when your use formatter function, take four parameters:event:the jQuery event. value:the field value. Row:the row record data. Index:the row index.

Example Code:

{
field: ' Operate ',
title: ' Item operate ',
align: ' center ',
events:operateevents,
formatter: Operateformatter
}
function Operateformatter (value, row, index) {return
[
' <a class= ' like ' href= ' Javascript:void (0) "title=" like ">",
' <i class= ' Glyphicon glyphicon-heart ' ></i> ',
' </a > ',
' <a class= ' remove ' href= ' javascript:void (0) ' title= ' Remove ' > ',
' <i class= ' Glyphicon Glyphicon-remove "></i>",
' </a> '
].join (');
}
window.operateevents = {
' click ': Function (E, value, row, index) {
alert (' Click Like Action, row: ' + Json.stringify (Row));
},
' click. Remove ': function (E, value, row, index) {
$table. bootstraptable (' Remove ', {
field: ' ID ',
values: [Row.id]
};
}
;

Handle the handling of events that exist in the system, which are stated in the document

$ (' #table '). Bootstraptable ({
oneventname:function (arg1, arg2, ...) {
// ...
}
});
$ (' #table '). On (' Event-name.bs.table ', function (E, arg1, arg2, ...) {
// ...
});

There are many in this name document!

Onall all.bs.table 
name, args 
fires when all events trigger, the parameters contain: 
name:the event Name,
   args:the event data.

Handle some methods, such as how many rows are currently selected, select All, and so on

The calling method is syntax: $ (' #table '). Bootstraptable (' method ', parameter);

1 ID of the currently selected box

Getselections None return selected rows, where no record selected, a empty array would return.

2. Select All

Getallselections None return all selected rows contain search or filter, where no record selected, a empty array would retu RN.
$table. On (' All.bs.table ', function (e, name, args) {
console.log (name, args);
});

3. Delete the foreground data, do not need to reload from the background

Remove params remove data from table, the params contains two properties: 
field:the field name of remove rows. 
Values:the array of values for rows which should is removed.

..... Lots and lots of things!

A Delete button to delete all the selected events! is not very good!

function Getidselections () {return
$.map ($table. bootstraptable (' getselections '), function (row) {
return Row.id
});
$remove. Click (function () {
var ids = Getidselections ();
$table. Bootstraptable (' Remove ', {
field: ' ID ',
values:ids
});
$remove. Prop (' disabled ', true);
};

The above is a small set to introduce the summary of the use of bootstrap table, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.