JS Table component bootstraptable in-line editing solution X-editable_javascript Tips

Source: Internet
Author: User
Tags eval extend locale line editor

Preface: Before introducing the bootstraptable component, it has mentioned its inline editing function, just for the purpose of displaying the function, it has been brought over, the crime is a sin! The recent project inside or intend to use up the line editor, so again studied the next X-editable components, encountered some pits, and then make a pit record! Want to know bootstraptable friend can go to JS Component Series-table component artifact: Bootstrap table.

introduction of X-editable Components

The X-editable component is a plug-in for creating an editable pop-up box that supports three styles: bootstrap, jquery UI, jquery. The approximate effect is as follows:

According to the usual style of bloggers, this is definitely the first choice. First of all, give the open source address.
X-editable Open Source Address: https://github.com/vitalets/x-editable
X-editable Document Address: http://vitalets.github.io/x-editable/docs.html
X-editable Online demo:http://vitalets.github.io/x-editable/demo-bs3.html

1, x-editable first experience

First download the source based on Bootstrap to the local. Refer to related files.

<link href= "/content/bootstrap/css/bootstrap.min.css" rel= "stylesheet"/> <link href=
"~/Content/" Bootstrap3-editable/css/bootstrap-editable.css "rel=" stylesheet "/>

<script src="/scripts/ Jquery-1.9.1.min.js "></script>
<script src="/content/bootstrap/js/bootstrap.min.js "></ script>
<script src= "~/content/bootstrap3-editable/js/bootstrap-editable.js" ></script> 

Page elements

Copy Code code as follows:
<a href= "#" id= "username" data-type= "text" data-title= "username" > Username </a>

JS Initialization

 $ (function () {
  $ (' #username '). editable ();

Effect Show

The above is through the HTML Data property to set the x-editable parameters, of course, I can also set the parameters in the initialization, for example, I just give an empty a tag: <a href= "#" id= "username" > Username </a >

JS Initialization

 $ (function () {
  $ (' #username '). Editable ({
   type: "Text",    //edit box type.) Support Text|textarea|select|date|checklist such title
   : "User name",    ///edit box title
   Disabled:false,//    Disable edit
   Emptytext: "Empty text",   //null value default text mode
   : "inline",    //edit box pattern: Support Popup and inline two modes, default is popup
   validate: function (value) {//field validation
    if (!$.trim (value) {return
     ' cannot be empty ';


View Effects

A little more complicated.
<a href= "#" id= "Department" > select Department </a>

 $ (function () {
  $ (' #department '). Editable ({type
   : SELECT,    //edit box type.) Support Text|textarea|select|date|checklist
   Source: [{value:1, Text: Development department}, {value:2, Text: Sales department}, {value:3,text: "line Political Department "}", Title
   : "Select Department",   ///edit box title
   Disabled:false,//   Disable edit
   emptytext: "Empty text",  //null value default text Mode
   : Popup,   //edit box pattern: Supports popup and inline two modes, default is popup
   validate:function (value) {//field validation
    if (!$). Trim (value)) {return
     ' cannot be empty ';}}});


View Effects

The above only gives some commonly used fields, of course, x-editable components have many other functional parameters, interested to see the document, the official document for each parameter has a detailed description.

Second, bootstraptable in-line editing initial scheme

Said such a long time, the above is only foreshadowing, we ultimately hope that in bootstraptable inside the implementation of inline editing. According to the rules above, we want to use x-editable to implement inline editing, the table cell must have a label inside it, and then do a x-editable initialization of the A tag. With this idea in mind, let's try this idea first.

Referencing related files

<link href= "/content/bootstrap/css/bootstrap.min.css" rel= "stylesheet"/> <link href=
"~/Content/" Bootstrap3-editable/css/bootstrap-editable.css "rel=" stylesheet "/>
<link href="/content/ Bootstrap-table/bootstrap-table.min.css "rel=" stylesheet "/> <script src="/scripts/jquery-1.9.1.min.js "

<script src= "/content/bootstrap/js/bootstrap.min.js" ></script>
< Script src= "~/content/bootstrap3-editable/js/bootstrap-editable.js" ></script>
<script src= "~/ Content/bootstrap-table/bootstrap-table.js "></script>
<script src="/content/bootstrap-table/ Locale/bootstrap-table-zh-cn.js "></script>

Bootstraptable related initialization

<script type= "Text/javascript" > var currow = {}; $ (function () {$ ("#tb_user"). Bootstraptable ({toolbar: "#toolbar", IDfield: "Id", Pagination:true, ShowRef
   Resh:true, Search:true, Clicktoselect:true, queryparams:function (param) {return {}; }, URL: "/editable/getusers", columns: [{checkbox:true}, {field: "UserName", Title: "Username", fo Rmatter:function (value, row, index) {return "<a href=\" #\ "name=\" username\ "data-type=\" text\ "data-pk=\" "+row" .
    Id+ "\" "data-title=\" user name \ ">" + value + "</a>"; }, {field: ' Age ', Title: ' Ages ',}, {field: ' Birthday ', title: ' Birthday ', formatter:function (valu
    E, row, index) {var date = eval (' new ' + eval (value). Source) return Date.format ("YYYY year mm month DD Day"); }, {field: "Deptname", Title: "Department"}, {field: "Hodd", Title: "Hobby"}], onclickrow:funct
   Ion (row, $element) {currow = row; The OnLoadSuccess:function (AA, BB, cc) {$ ("#tb_user a"). Editable ({url:function (params) {var sname = $ (this). at
      TR ("name");
      Currow[sname] = Params.value; $.ajax ({type: ' POST ', url: "/editable/edit", Data:currow, DataType: ' JSON ', success: function (data, textstatus, JQXHR) {alert (' Save success!
      }, Error:function () {alert ("error");}
   }, type: ' Text '};


Background method

Background test method

Public Jsonresult getusers () {var lstres = new list<user> (); Lstres.add (New User () {Id = "1", UserName = "John", age = =, Birthday = Convert.todatetime ("1994-12-21"), DeptID = "1", De
   Ptname = "Research and Development Department"}); Lstres.add (New User () {Id = "2", UserName = "Dick", age =, birthday = Convert.todatetime ("1988-09-09"), DeptID = "2", De
   Ptname = "Sales Department"}); Lstres.add (New User () {Id = "3", UserName = "Uncle Windbreaker", age =, birthday = Convert.todatetime ("1976-09-01"), DeptID = "2",
   Deptname = "Sales Department"}); Lstres.add (New User () {Id = "4", UserName = "lightning prawn", age = Panax Notoginseng, birthday = Convert.todatetime ("1979-03-12"), DeptID = "4",
   Deptname = "creative Department"}); Lstres.add (New User () {Id = "5", UserName = "Han Meimei", age = yes, birthday = Convert.todatetime ("1987-05-01"), DeptID = "5", D

   Eptname = "business Unit"});
  Return Json (Lstres, jsonrequestbehavior.allowget);
  Update return Json (new {}, Jsonrequestbehavior.allowget) after Jsonresult Edit (user user) {//deserialization; }

This is really possible to achieve the desired effect, seemingly also can be edited in line, but if no columns need to edit the line, and the number of columns, then is not each column have to Formmater? And this kind of writing ruthless apparently very rigid, the blogger really difficult to accept. Then looked for an example, found in the bootstraptable expansion of the existence of bootstrap-table-editable.js this JS.

Iii. Bootstraptable in-line editing final plan

Well, the blogger admits that it's still the groundwork, because bloggers think this may be the general way to solve the problem, so there may be a little more space for these bedding. First look at bootstrap-table-editable.js this file:

/** * @author zhixin Wen <wenzhixin2010@gmail.com> * extensions:https://github.com/vitalets/x-editable * *!fun

 Ction ($) {' Use strict ';
  $.extend ($.fn.bootstraptable.defaults, {editable:true, oneditableinit:function () {return false;
  }, Oneditablesave:function (field, row, OldValue, $el) {return false;
  }, Oneditableshown:function (field, row, $el, editable) {return false;
  }, Oneditablehidden:function (field, row, $el, reason) {return false;

 }); $.extend ($.fn.bootstraptable.constructor.events, {' editable-init.bs.table '): ' Oneditableinit ', ' Editable-save.bs.table ': ' Oneditablesave ', ' editable-shown.bs.table ': ' Oneditableshown ', ' editable-hidden.bs.table

 ': ' Oneditablehidden '}); var bootstraptable = $.fn.bootstraptable.constructor, _inittable = BootstrapTable.prototype.initTable, _initbody = Boo

  BootstrapTable.prototype.initTable = function () {var = this; _inittable.apply(This, Array.prototype.slice.apply (arguments));
  if (!this.options.editable) {return;
   } $.each (This.columns, function (i, column) {if (!column.editable) {return;
   var _formatter = Column.formatter;

    Column.formatter = function (value, row, index) {var result = _formatter? _formatter (value, row, index): value; return [' <a href= ' javascript:void (0) "', ' data-name= ' + Column.field + '" ', ' data-pk= ' + row[that.optio
   Ns.idfield] + ' "', ' data-value= ' + result + '" ', ' > ' + ' </a> '].join (');

  BootstrapTable.prototype.initBody = function () {var = this;

  _initbody.apply (This, Array.prototype.slice.apply (arguments));
  if (!this.options.editable) {return;
   } $.each (This.columns, function (i, column) {if (!column.editable) {return; $body. Find (' a[data-name= "' + Column.field + '"]). Editable (column.editable)-Off (' save '). On (' Save ', functio
  N (E, params) {   var data = That.getdata (), index = $ (this). Parents (' tr[data-index] '). Data (' index '), row = Data[index],

     OldValue = Row[column.field];
     Row[column.field] = Params.submitvalue;
    That.trigger (' Editable-save ', Column.field, Row, OldValue, $ (this));
   }); $body. Find (' a[data-name= ' + Column.field + ' "]). Editable (column.editable). Off (' shown '), function ( E, editable) {var data = That.getdata (), index = $ (this). Parents (' tr[data-index] '). Data (' index '), row =
    That.trigger (' Editable-shown ', Column.field, Row, $ (this), editable);
   }); $body. Find (' a[data-name= "' + Column.field + '] '). Editable (column.editable)-Off (' hidden '). On (' Hidden '),
      function (e, reason) {var data = That.getdata (), index = $ (this). Parents (' tr[data-index] '). Data (' index '),
     row = Data[index];
    That.trigger (' Editable-hidden ', Column.field, Row, $ (this), reason);
  }); This.trigger (' EDitable-init ');


 } (JQuery);

This JS is actually a simple encapsulation of the x-editable, adding the column's editable properties and editing some of the saved events. With this as the basis, so we edit the code in the line into this.

The files that need to be referenced are as follows:

<link href= "/content/bootstrap/css/bootstrap.min.css" rel= "stylesheet"/> <link href=
"~/Content/" Bootstrap3-editable/css/bootstrap-editable.css "rel=" stylesheet "/>
<link href="/content/ Bootstrap-table/bootstrap-table.min.css "rel=" stylesheet "/> <script src="/scripts/jquery-1.9.1.min.js "

<script src= "/content/bootstrap/js/bootstrap.min.js" ></script>
< Script src= "~/content/bootstrap3-editable/js/bootstrap-editable.js" ></script>
<script src= "~/ Content/bootstrap-table/bootstrap-table.js "></script>
<script src="/content/bootstrap-table/ Locale/bootstrap-table-zh-cn.js "></script>
<script src=" ~/content/bootstrap-table/extensions/ Editable/bootstrap-table-editable.js "></script>

1. Text Box

  $ (function () {$ ("#tb_user"). Bootstraptable ({toolbar: "#toolbar", IDfield: "Id", Pagination:true, show
   Refresh:true, Search:true, Clicktoselect:true, queryparams:function (param) {return {}; }, URL: "/editable/getusers", columns: [{checkbox:true}, {field: "UserName", Title: "User Name", ed

     Itable: {type: ' text ', Title: ' Username ', validate:function (v) {if (!v) return ' username cannot be null ';  }}, {field: ' Age ', Title: ' Ages ',}, {field: ' Birthday ', title: ' Birthday ', formatter:function (value, row, index)
    {var date = eval (' new ' + eval (value). Source) return Date.format ("Yyyy-mm-dd"); }, {field: "Deptname", Title: "Department"}, {field: "Hobby", Title: "Hobby"}], Oneditablesa
     Ve:function (field, row, OldValue, $el) {$.ajax ({type: "post", url: "/editable/edit", Data:row, DataType: ' JSON ', success:function (data, Status {if (status = = "Success") {alert (' successful submission data ');
     }, Error:function () {alert (' edit failed ');
   }, Complete:function () {}});


Backend corresponding Update method

   Public Jsonresult Edit (user user)
   //Update entity return

   Json (new {}, Jsonrequestbehavior.allowget);

After testing, the user name this column is basically free to edit. Similarly, the age of this column can also be changed to this

    field: ' Age ',
    title: ' Ages ',
    editable: {
     type: ' Text ',
     title: ' Age ',
     validate:function (v) {
      if (isNaN (v)) Return ' age must be a number ';
      var age = parseint (v);
      if (age <= 0) return ' must be a positive integer ';}}

Other basic do not have to do any modification.
Code explanation: Above in the initialization of the Columns property to configure editable parameters with the editable property, note that the JSON object for each column's editable attribute is the initialized JSON object in X-editable. That is, we initialize the x-editable can configure which properties, in the column of the editable properties can also be configured, so it is much more fun to use it. The edited submission method is uniformly disposed in the Oneditablesave event.

2, Time selection box

With the above knowledge as the foundation, let's initialize the column of birthdays:

    field: "Birthday",
    title: "Birthday",
    formatter:function (value, row, index) {
     var date = eval (' new ' + eval ( Value). Source) return
     Date.format ("Yyyy-mm-dd");
    editable: {
     type: ' Date ',
     title: ' Birthday '

Other places do not have to make any changes to get the effect:

This is the default style of x-editable, if you look uncomfortable, you can configure yourself, X-editable provides a number of parameters for the configuration date box, as follows:

Of course, you can use the DateTime type edit box if you are accurate to the time and minutes. The following is the official given time frame editing effect, look good.

3. Drop down box

Another important tag in the Form editor is select. We know from the above that X-editable provides us with the edit mode of the dropdown box, for example, our department editor can write this:

    field: "DeptID",
    title: "Department",
    editable: {
     type: ' select ',
     title: ' Department ',
     source:[{value: ' 1 ' , Text: "Research and Development Department"},{value: "2", Text: "Sales Department"},{value: "3", Text: "Administrative department"}}

Get effect

Of course, this method of setting up data sources locally is certainly not up to our needs, because in many cases the options in the dropdown box are obtained remotely from the database. Of course x-editable also for us to consider, for example we can write:

    field: "DeptID",
    title: "Department",
    editable: {
     type: ' select ',
     title: ' Department ',
     Source: function () {
      var result = [];
      $.ajax ({
       URL: '/editable/getdepartments ',
       type: ' Get ',
       data: {},
       success: function (data, status) {
        $.each (data, function (key, value) {
         Result.push {value:value.ID, text:value. Name
      ); return result

Backstage we configure a method

  Public Jsonresult getdepartments ()
   var lstres = new list<department> ();
   Lstres.add (New Department () {ID = "1", Name = "Research Department"});
   Lstres.add (New Department () {ID = "2", Name = "sales Department"});
   Lstres.add (New Department () {ID = "3", Name = "Administrative Department"});
   Lstres.add (New Department () {ID = "4", Name = "creative Department"});
   Lstres.add (New Department () {ID = "5", Name = "business Unit"});
   Return Json (Lstres, jsonrequestbehavior.allowget);

can also achieve the results we want.

Code Explanation: Here is a point to explain, careful garden friends may find, we here field: "DeptID", why here to configure DeptID instead of Deptname? Very simple, because we need to correspond to the value values in the data source.

4, check box

In addition to the several common editing boxes mentioned above, X-editable also provides us with the check box group edit. Like what:

    field: "Hobby",
    title: "Hobby",
    editable: {
     type: "Checklist",
     separator: ",",
     Source: [{ Value: ' BSB ', Text: ' Basketball '},
       {value: ' FTb ', text: ' Soccer '},
       {value: ' WSM ', text: ' Swimming '}],

Get effect:

Of course, if you have remote data, you can use a method similar to the above to fetch it.

5, "haunting" of the Select2

Referring to the check box above, the blogger involuntarily and thought of multiselect these things, so look for x-editable documents, found that it does not support MultiSelect, but support select2, do not know if this is not a good news. According to the blogger's own experience, including the chat experience in the technical Exchange group, it is found that many people have encountered various style problems when using SELECT2, and are not very good at solving them.

Since x-editable support Select2, then we use to try Bai, anyway, the official demo is very good, the following is the official demo use example:

With disturbed mood, the blogger himself tried a hand.

Referencing Select2 files

 <link href= "~/content/select2-bootstrap.css" rel= "stylesheet"/> <link href=
"~/content/select2-master" /dist/css/select2.min.css "rel=" stylesheet "/>
<script src=" ~/content/select2-master/dist/js/ Select2.full.min.js "></script> 

Code attempts

    field: "Hobby",
    title: "Hobby",
    editable: {
     type: ' Select2 ',
     title: ' Hobby ',
     name: ' Hobby ',
     placement: ' Top ',
     success:function (response, NewValue) {
     error:function ( Response, NewValue) {
     url:function (params) {
     Source: [{ID: ' BSB ', Text: ' Basketball '},
        {id: ' FTB ', Text: ' Football '},
        {id: ' WSM ', text: ' Swim '}],
     inputclass: ' Input-large ', 
    select2: {

Get the result:

The results found that Select2 's selected values were not passed to the background correctly. Anyway, bloggers tried various parameters, according to the official demo of the writing also tried, all failed. I don't know how the official demo was successful. This question is thrown first, if there is a use of garden friends welcome correction and answer. Later if the blogger solves this problem, it will also be updated here.

Iv. Summary

Another problem is that after the editor completes the submission, the blogger encounters a problem with the project: if there is too much text after the submission, the thead inside the table and the width of the TD inside the tbody are not the problem, it looks rather disgusting. But I didn't get this problem when I was writing the demo. Here's the solution.

That's the way to solve your problems!

This article introduces the use of bootstraptable and x-editable to implement inline editing. Many of the problems are based on the use of the blogger has always been explained, if you intend to use it, you can try.

The above is the entire content of this article, I hope to help you better learn the JS Table component Artifact bootstrap table.

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.