Use jquery to implement simple editable tables based on Bootstrap

Source: Internet
Author: User

Edittable.js provides an action to edit the current row of the table, add a row, delete the current row, where you can set parameters such as:

The Operatepos is used to set the column for the drop operation, starting with 0, 1 representing the column with the last column as the drop operation, where the action includes editing the current row, adding a row below the current line, and deleting the current row.

Handlefirst sets whether the first row of the table is an object of action, True is true, False is false;

Edit, save, Cancel, add, confirm, Del respectively set the action name of the display operation, the default display "edit", "Save", "Cancel", "Add", "Confirm", "delete" the words;

Editablecols sets the columns that can be edited, starting with 0, set as an array, such as [1, 2], which can be edited when the 2nd and 3 columns are edited, and can pass "all", which means that all columns are selected for editing, and the columns that have been set to be placed are automatically excluded from the program;

Order sets the operation required for the table, and can set the order of the operation emissions, the parameter is an array, the value can be edit, add, Del, the input empty array, the default provides edit editing operation, equivalent to set ["edit"] parameter, and by default provides all functions, namely, edit, Add, delete, equivalent to set ["Edit", "Add", "del"] parameters, and order for edit-"add-" Delete, you can modify the order of the three, such as ["Add", "Edit", "Del"];

Savecallback when editing is provided, in the process of editing the current line, click on the saved callback function, the user needs to use the editing function while setting this parameter, when it is saved, the function can use Ajax to pass the edited data (stored in data array), It should also be necessary to invoke the Issuccess method in the function parameter when Ajax saves the data, in order to modify the editable state in the interface to be non-editable.

Addcallback and Delcallback, like Savecallback, are only applied to different operations--add and delete.

Edittable.js

/** * Created by Dreamboy on 2016/4/19.            */$ (function () {$.fn.handletable = function (options) {//1.settings initialization set var c = $.extend ({            "Operatepos":-1,//-1 indicates that the default action is listed as the last column "Handlefirst": false,//whether the first row is an object of action "edit": "Editing",             "Save": "Saved", "Cancel": "Cancel", "Add": "added", "Confirm": "Confirm", "del": "Delete", "Editablecols": "All",//Editable column, starting from 0//"POS": 0,//position at the beginning of the column, or end (left or right) "order": ["EDI                T "," Add "," Del "],//Specify the order of three functions" Savecallback ": function (data, issuccess) {//Here you can write Ajax content to save the edited content Data://issuccess: Method to save data successfully, change the editable state to non-editable state//ajax request succeeded (save data successfully), only callback issuccess letter Number (Modify save state to edit state)}, "Addcallback": function (data, issuccess) {//issuccess: method, for adding data into After work, the editable state is changed to a non-editable state}, "Delcallback": function (issuccess) {//issuccesS: method to delete the data after successful, the corresponding row will be deleted}}, Options);        Number of columns in the table var Colsnum = $ (this). Find (' tr '). Last (). Children (). Size ();        2. Initialize the Action column, default to the last column, from 1 for if (C.operatepos = =-1) {c.operatepos = colsNum-1;        }//3. Get all rows that need to be manipulated var rows = $ (this). Find (' tr ');        if (!c.handlefirst) {rows = Rows.not (": eq (0)");        //4. Get the column that puts the "action", get var rowstd by operatepos = [];        var alltd = Rows.children ();                for (var i = c.operatepos; I <= alltd.size (); i + = Colsnum) {if (C.handlefirst) {///if the first line of operation, the column contents of the drop operation are left blank            Alltd.eq (i). HTML ("");        } rowstd.push (Alltd.eq (i) [0]);        }//6. Modify the default value if the order is empty if (C.order.length = = 0) {C.order = ["edit"];        }//7. Save editable column var cols = Geteditablecols ();        8. Initialize the link build var savelink = "", Cancellink = "", Editlink = "", Addlink = "", Confirmlink = "", Dellink = ""; InitLink ();        9. Initialize Operation Initfunc (C.order, ROWSTD); /** * Create action link */function createlink (str) {return "<a href=\" javascript:void (0) \ "sty Le=\ "margin:0        3px\ ">" + str + "</a>"; }/** * Initial various operations of the link */function Initlink () {for (var i = 0; i < c.order.length;                        i++) {switch (C.order[i]) {case ' edit '://' edit ' link                        Editlink = Createlink (C.edit);                        Savelink = Createlink (c.save);                        Cancellink = Createlink (C.cancel);                    Break                        Case "Add"://"Add" link Addlink = Createlink (C.add);                        "Confirmation" link Confirmlink = Createlink (c.confirm);                        "Cancel" link Cancellink = Createlink (C.cancel);      Break              Case "Del"://"delete" link Dellink = Createlink (C.del);                Break }}}/** * Get columns for editing operations */function Geteditablecols () {var col            s = c.editablecols;                if ($.type (c.editablecols) = "Array" && cols = = "All") {//* If all columns can be edited cols = []; for (var i = 0; i < Colsnum; i++) {if (i! = C.operatepos) {//Exclude drop action columns COLS.P                    Ush (i); }}}} else if ($.type (c.editablecols) = = "Array") {//There are columns that you specify to select the edits you want to sort the column VA to place the "edit" function                R copycols = []; for (var i = 0; i < cols.length; i++) {if (cols[i]! = C.operatepos) {Copycols                    . push (Cols[i]);            }} cols = Copycols;        } return cols;    }        /**     * Operation provided according to the C.order parameter * @param func needs to set the action * @param the column of cols placement action */function Initfunc (f                UNC, cols) {for (var i = 0; i < func.length; i++) {var o = func[i];                        Switch (o) {case "edit": CreateEdit (cols);                    Break                        Case "Add": Createadd (cols);                    Break                        Case "Del": Createdel (cols);                Break }}}/** * create "edit one line" function * @param operatecol the column where the edit action is placed */function C Reateedit (Operatecol) {$ (Editlink). AppendTo (Operatecol). On ("click", Function () {if (Replacequot E ($ (this). HTML ()) = = Replacequote (c.edit)) {//If this is the edit state tosave (this);//Change the edit state to a saved state} E LSE if (Replacequote (this). HTML ()) = = Replacequote (c.save)) {//IFThis is the save state var p = $ (this). Parents (' tr '); Gets the current row being clicked var data = []; Save the modified data within the data for (var i = 0; i < cols.length; i++) {var tr = P.children (). E                        Q (Cols[i]);                        var inputvalue = tr.children (' input '). Val ();                    Data.push (Inputvalue); } $this = this;                    This is the edited link c.savecallback (data, function () {Toedit ($this, True) that is clicked;                });            }            }); var aftersave = []; Save the pre-modification information for the user to click on the cancel value returned action//modified to "save" status function Tosave (ele) {$ (ele). HTML (c.save); /modified to "save" $ (ele). After (Cancellink); Add the corresponding cancel saved "unlink" $ (ele). Next (). On (' click ', Function () {//if ($ ()). html () = = C.cance                    L.replace (eval ("/\ '/gi"), "\" ")) {Toedit (ele, false);//}                });                Gets the current line that is clicked to edit the TR jquery object var p = $ (ele). Parents (' tr '); Aftersave = [];                     Empty the original saved data for (var i = 0; i < cols.length; i++) {var tr = P.children (). EQ (cols[i]);                    var edittr = "<input type=\" text\ "class=\" form-control\ "value=\" "+ tr.html () +" \ "/>"; Aftersave.push (tr.html ());                Save the Data tr.html (edittr) before modification;            }}//modified to "edit" status (at this point, you need to determine by the ISSAVE flag is//Because the click on "Save" (saved successfully) to "edit" status, or because the click "Cancel" to "edit" status)                function Toedit (ele, Issave) {$ (ele). HTML (c.edit);                if (Replacequote ($ (ele). Next (). HTML ()) = = Replacequote (c.cancel)) {$ (ele). Next (). Remove ();                } var p = $ (ele). Parents (' tr ');                    for (var i = 0; i < cols.length; i++) {var tr = P.children (). EQ (cols[i]);var value;                    if (issave) {value = Tr.children (' input '). Val ();                    } else {value = Aftersave[i];                } tr.html (value); }}}/** * create "Add a line" function * @param operatecol */function Createadd ( Operatecol) {$ (Addlink). AppendTo (Operatecol). On ("click", Function () {//Get clicked "Add" on the current line TR JQuery                The object var p = $ (this). Parents (' tr '); var copyrow = P.clone ();                Build a new line var input = "<input type=\" text\ "/>";                var Childlen = P.children (). length; for (var i = 0; i < Childlen; i++) {Copyrow.children (). EQ (i). HTML ("<input type=\" text\ "class=\" f                Orm-control\ "/>");                }//The last line is the operation row var = copyrow.children (). EQ (c.operatepos);        Last.html ("");        P.after (Copyrow);                    var confirm = $ (confirmlink). AppendTo (last). On ("click", Function () {var data = []; for (var i = 0; i < Childlen; i++) {if (i! = C.operatepos) {var v =                            Copyrow.children (). EQ (i). Children ("input"). Val ();                            Data.push (v);                        Copyrow.children (). EQ (i). html (v);                        }} c.addcallback (data, function () {last.html ("");                    ------------can be modified here Initfunc (C.order, last);                });                }); $ (confirm). After (Cancellink);                Add the corresponding cancel saved "unlink" $ (confirm). Next (). On (' click ', Function () {copyrow.remove ();            });        }); }/** * Create a "delete Row" function * @param operatecol */function CREatedel (Operatecol) {$ (Dellink). AppendTo (Operatecol). On (' click ', function () {var _this = this;                C.delcallback (function () {$ (_this). Parents (' tr '). Remove ();            });        }); /** * Convert single quotation marks in STR to double quotes * @param str */function Replacequote (str) {retur        N str.replace (/\ '/g, "\" "); }    };});


You need to be aware of the need to include selectable selectors in the corresponding table, as well as the need to place an empty label on the column where the action is placed <td></td> to hold the action.

The use cases are as follows:

Directory structure:


Index.html

<! DOCTYPE html>
The results of the operation are as follows:


To use the edit operation:


To modify:


Click Save:


Add multiple lines:


Add some data to it:


Click "OK":



You can cancel additional rows that you want to add:




Use jquery to implement simple editable tables based on Bootstrap

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.