jQuery.edittable 是一个可以实时编辑Table表格的jQuery插件

jQuery.edittable 是一个可以实时编辑Table表格的jQuery插件

jQuery.edittable 是一个可以实时编辑Table表格的jQuery插件,支持实时编辑表格的内容,而且能够随意增加行和列。

使用方式:

第一步引入依赖项jquery和插件css及js

<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jquery-3.2.1.min.js"></script>
<link type="text/css" rel="stylesheet" href="//repo.bfw.wiki/bfwrepo/css/jquery.edittable.min.css">
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jquery.edittable.min.js"></script>

第二步配置参数

var mytable = $('#edittable').editTable({
data: [['']], // 表格内容数组
tableClass: 'inputtable', // Table 表格classname
jsonData: false, //填充json数据(会被上面data数组覆盖)
headerCols: false, // 表格头是否显示
maxRows: 999, // 最大行数
first_row: true, //第一行是否加粗高亮显示
row_template: false, //行模板是否启用
field_templates: false, //列模板是否启用

//验证字段
validate_field: function (col_id, value, col_type, $element) {
return true;
}
});

方法:

mytable.loadData(dataArray); //数据填充数据
mytable.loadJsonData(jsonData); // json数组填充
mytable.getData(); //获取表格数据
mytable.getJsonData(); // 获取json表格数据
mytable.reset(); // 重设
mytable.isValidated() // 验证

如果要自定义字段时这样的

[
'checkbox' : {

  html: '<input type="checkbox"/>', // Input type html

// How to get the value from the custom input
    getValue: function (input) {
       return $(input).is(':checked');
  },

  // How to set the value of the custom input
  setValue: function (input, value) {
    if ( value ){
      return $(input).attr('checked', true);
    }
    return $(input).removeAttr('checked');
    }
   }
]

简单示例代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>BFW NEW PAGE</title>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jquery-3.2.1.min.js"></script>
    <link type="text/css" rel="stylesheet" href="//repo.bfw.wiki/bfwrepo/css/jquery.edittable.min.css">
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jquery.edittable.min.js"></script>


    <script type="text/javascript">
        $(function() {
            $("#edittable2").editTable({
                data: [
                    ["01/01/2013", "01/30/2013", "50,00"],
                    ["02/01/2013", "02/28/2013", "50,00 "],
                    ["02/01/2013", "02/28/2013", "50,00 "],
                    ["02/01/2013", "02/28/2013", "50,00 "],
                    ["02/01/2013", "02/28/2013", "50,00 "],
                    ["02/01/2013", "02/28/2013", "50,00 "]
                ],
                headerCols: [
                    'From',
                    'To',
                    'Price'
                ],
                first_row: false,
                maxRows: 7
            });

        })
    </script>
    <style>
    </style>
</head>
<body>
    <div id="edittable2">

    </body>
</html>

完整用法示例代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <title>jQuery editTable</title>
    <style>
        body {
            font-family: "Helvetica Neue";
        }
        .container {
            margin: 0 auto;
            width: 90%;
            padding: 0 5% 20px 5%;
            max-width: 960px;
        }

        a {
            text-decoration: none;
            color: #4988C6;
        }
        p {
            color: #444;
        }
        h1 span {
            color: #ddd;
            font-size: 26px;
        }

        .title {
            font-weight: 800;
            font-size: 12px;
            text-transform: uppercase;
            padding: 15px 0 0 0;
            display: block;
        }
        pre {
            background-color: #fafafa;
            padding: 20px;
            overflow: auto;
            border: 1px solid #f1f1f1;
            color: #000;
        }
        .note {
            color: #999;
            font-size: 14px;
        }
        .download_button {
            padding: 15px 0;
            background: #F2F2F2;
            display: block;
            margin: 30px auto;
            width: 100%;
            max-width: 200px;
            text-align: center;
            color: #4988C6;
            text-decoration: none;
            font-weight: 800;
            font-size: 12px;
            border-bottom: 3px solid #ddd;
        }
        .download_button:active {
            position: relative;
            top: 3px;
            border-bottom: 0;
        }
        .download_button:hover {
            background-color: #eaeaea;
        }

        button, a.button {
            border: none;
            padding: 0 20px;
            height: 40px;
            background-color: #eee;
            color: #333;
            text-decoration: none;
            display: inline-block;
            line-height: 40px;
            margin: 0;
            vertical-align: top;
            font-weight: 200;
            border-bottom: 1px solid #ddd;
            font-family: "Helvetica Neue";
            -moz-box-sizing: content-box;
            -webkit-box-sizing: content-box;
            box-sizing: content-box;
            font-size: 14px;
            cursor: pointer;
            margin: 5px 0;
        }
        button::-moz-focus-inner {
            border: 0px;
        }
        button:hover, a.button:hover {
            background-color: #f1f1f1;
        }
        button:active, a.button:active {
            background-color: #e9e9e9;
        }
        textarea {
            width: 98%;
            height: 100px;
            padding: 1%;
            border: 1px solid #eee;
        }
        #ui-datepicker-div {
            font-size: 12px;
        }
        .examplecode {
            padding: 15px 2%;
            background-color: #fffef1;
            border-top: 2px dotted #eee;
            border-bottom: 2px dotted #eee;
            margin-top: 10px;
        }
        .examplecode pre {
            background-color: #ffffff;
        }
        hr {
            border: 0;
            margin-top: 20px;
            color: #eee;
            background-color: #eee;
            height: 3px;
        }
        .inputtable.custom textarea {
            width: 96%;
            margin: 0;
            padding: 5px 2%;
            border: 0;
            resize: none;
            height: 100px;
        }
        .inputtable.custom textarea:focus {
            background-color: #fafafa;
        }
        .inputtable.custom input[type=text] {
            height: 110px;
        }
    </style>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jquery.edittable.min.js"></script>
    <script type="text/javascript" src="../jquery.edittable.js?v=0.2.0"></script>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jquery-ui-1.11.0.min.js"></script>
    <link type="text/css" rel="stylesheet" href="//repo.bfw.wiki/bfwrepo/css/jquery.edittable.min.css">
    <link type="text/css" rel="stylesheet" href="//repo.bfw.wiki/bfwrepo/css/jquery-ui.css">
    <script>
        $(window).ready(function () {

            // Initialize table example 0
            $('#source').editTable();

            // Initialize table example 1
            var eTable = $('#edittable').editTable({
                data: [
                    ["Click on the plus symbols on the top and right to add cols or rows"]
                ]
            });

            // Load json data trough an ajax call
            $('.loadjson').click(function () {
                var _this = $(this), text = $(this).text();
                $(this).text('Loading...');
                $.ajax({
                    url: 'data.json',
                    type: 'GET',
                    data: {
                        ajax: true
                    },
                    complete: function (result) {
                        _this.text(text);
                        eTable.loadJsonData(result.responseText);
                    }
                });
                return false;
            });

            // Reset table data
            $('.reset').click(function () {
                eTable.reset();
                return false;
            });

            // Initialize table example 2
            $("#edittable2").editTable({
                data: [
                    ["01/01/2013", "01/30/2013", "50,00 €"],
                    ["02/01/2013", "02/28/2013", "50,00 €"]
                ],
                headerCols: [
                    'From',
                    'To',
                    'Price'
                ],
                first_row: false,
                maxRows: 3
            });

            // Example of jQuery UI
            $("#edittable2").on("focusin", "td:nth-child(1) input, td:nth-child(2) input", function() {
                $(this).datepicker();
            });

            // Example 4
            // Custom fields & validation
            var mynewtable = $('#examplex').editTable({
                field_templates: {
                    'checkbox': {
                        html: '<input type="checkbox"/>',
                        getValue: function (input) {
                            return $(input).is(':checked');
                        },
                        setValue: function (input, value) {
                            if (value) {
                                return $(input).attr('checked', true);
                            }
                            return $(input).removeAttr('checked');
                        }
                    },
                    'textarea': {
                        html: '<textarea/>',
                        getValue: function (input) {
                            return $(input).val();
                        },
                        setValue: function (input, value) {
                            return $(input).text(value);
                        }
                    },
                    'select': {
                        html: '<select><option value="">None</option><option>All</option></select>',
                        getValue: function (input) {
                            return $(input).val();
                        },
                        setValue: function (input, value) {
                            var select = $(input);
                            select.find('option').filter(function() {
                                return $(this).val() == value;
                            }).attr('selected', true);
                            return select;
                        }
                    }
                },
                row_template: ['checkbox',
                    'text',
                    'text',
                    'textarea',
                    'select'],
                headerCols: ['Yes/No',
                    'Date',
                    'Value',
                    'Description',
                    'Which?'],
                first_row: false,
                data: [
                    [false,
                        "01/30/2013",
                        "50,00 €",
                        "Lorem ipsum...\n\nDonec in dui nisl. Nam ac libero eget magna iaculis faucibus eu non arcu. Proin sed diam ut nisl scelerisque fermentum."],
                    [true,
                        "02/28/2013",
                        "50,00 €",
                        'This is a <textarea>',
                        'All']
                ],
                validate_field: function (col_id, value, col_type, $element) {
                    if (col_type === 'checkbox') {
                        $element.parent('td').animate({
                            'background-color': '#fff'
                        });
                        if (value === false) {
                            $element.parent('td').animate({
                                'background-color': '#DB4A39'
                            });
                            return false;
                        }
                    }
                    return true;
                },
                tableClass: 'inputtable custom'
            });

            $('#examplexconsole').click(function(e) {
                console.log(mynewtable.getData());
                if (!mynewtable.isValidated()) {
                    alert('Not validated');
                }
                e.preventDefault();
            });

            $('.showcode').click(function () {
                $($(this).attr('href')).slideToggle(300);
                return false;
            });

        });
    </script>
</head>

<body>

    <div class="container">

        <h1>jQuery editTable <span>v0.2.0</span></h1>





        <p>
            That's it, now give a look to the following examples to understand how it works.
        </p>

        <hr>

        <h3>Example 1 - Basics</h3>

        <p>
            In the first example we'll implement the simplest HTML POST use of editTable. If you are looking to use editTable on ajax contest instead just give a look to the next example.
        </p>

        <form method="post" action="#output">
            <textarea id="source" style="display: none;" name="myField">[
                ["Carbon","Hydrogen","Nitrogen","Oxygen"],
                [10,15,1,0],
                [8,11,1,2],
                [10,15,1,1],
                [12,17,1,1],
                [14,19,1,2]
                ]</textarea>
            <button type="submit">Post data (and check your network tab)</button>
            <a href="#example0code" class="showcode button">Show Code</a>
        </form>

        <div id="example0code" style="display: none;" class="examplecode">
            <span class="title">INDEX.PHP</span>
            <pre>
                <form method="post" action="output.php">
                <textarea id="source" style="display:none" name="myField" ><?php
                echo json_encode(array(
                array('Period','Full Board', 'Half Board', 'Bed & Breakfast'),
                array('01/01 - 30/01','50.00 €', '40.00 €', '30.00 €'),
                array('01/02 - 28/02','55.00 €', '45.00 €', '35.00 €'),
                array('01/03 - 31/03','60.00 €', '50.00 €', '40.00 €'),
                array('01/04 - 30/04','55.00 €', '45.00 €', '35.00 €'),
                array('01/05 - 31/05','50.00 €', '40.00 €', '30.00 €')
                ));
                ?></textarea>
                <button type="submit">Send data</button>
                </form>
            </pre>

            <span class="title">SCRIPT.JS</span>
            <pre>
                $(window).ready(function () {
                $('#source').editTable();
                });
            </pre>

            <span class="title">OUTPUT.PHP</span>
            <pre>
                <?php var_dump( json_decode( stripslashes( $_POST['myField'] ) ) ); ?>
            </pre>

        </div>

        <hr>

        <h3>Example 2 - AJAX with editable columns:</h3>

        <div id="edittable"></div>
        <a href="#" class="loadjson button">Ajax load JSON</a>
        <a href="#" class="reset button">Reset Table</a>
        <a href="#example1code" class="showcode button">Show Code</a>

        <div id="example1code" style="display: none;" class="examplecode">
            <span class="title">index.htm</span>
            <pre>
                <div id="edittable"></div>
                <a href="#" class="sendjson button">Send JSON (check your console)</a>
                <a href="#" class="loadjson button">Load JSON from textarea</a>
                <a href="#" class="reset button">Reset Table</a>
            </pre>
            <span class="title">script.js</span>
            <pre>
                // Initialize table example 1
                var eTable = $('#edittable').editTable({
                data: [
                ["Click on the plus symbols on the top and right to add cols or rows"]
                ]
                });

                // Load json data trough an ajax call
                $('.loadjson').click(function () {
                var _this = $(this),text = $(this).text();
                $(this).text('Loading...');
                $.ajax({
                url: 	'output.php',
                type: 	'POST',
                data: 	{
                ajax: true
                },
                complete: function (result) {
                _this.text(text);
                eTable.loadJsonData(result.responseText);
                }
                });
                return false;
                });

                // Reset table data
                $('.reset').click(function () {
                eTable.reset();
                return false;
                });

                // Send JSON data trough an ajax call
                $('.sendjson').click(function () {
                $.ajax({
                url: 	'output.php',
                type: 	'POST',
                data: 	{
                ajax: true,
                data: eTable.getJsonData()
                },
                complete: function (result) {
                console.log(JSON.parse(result.responseText));
                }
                });
                return false;
                });
            </pre>
            <span class="title">output.php</span>
            <pre>
                <?php
                if ( isset( $_POST['ajax'] ) ){
                header( 'Content-Type: application/json' );
                if ( isset( $_REQUEST['data'] ) ){
                $data = json_decode( stripslashes( $_REQUEST['data'] ) );
                } else {
                $data = array(
                array('Carbon','Hydrogen','Nitrogen','Oxygen'),
                array(10,15,1,0),
                array(8,11,1,2),
                array(10,15,1,1),
                array(12,17,1,1),
                array(14,19,1,2)
                );
                }
                echo json_encode( $data );
                die();
                }
            </pre>

        </div>

        <hr>

        <h3>Example 3 - Fixed columns, Datepicker, Rows limit:</h3>

        <div id="edittable2"></div>
        <a href="#example2code" class="showcode button">Show Code</a>

        <div id="example2code" style="display: none;" class="examplecode">

            <span class="title">index.htm</span>
            <pre><div id="edittable2"></div></pre>

            <span class="title">script.js</span>
            <pre>
                // Initialize table example 3
                $("#edittable2").editTable({
                data: [
                ["01/01/2013","01/30/2013","50,00 €"],
                ["02/01/2013","02/28/2013","50,00 €"]
                ],
                headerCols: [
                'From',
                'To',
                'Price'
                ],
                maxRows: 3
                });

                // Example of jQuery UI datePicker
                $("#edittable2").on("focusin", "td:nth-child(1) input, td:nth-child(2) input", function(){
                $(this).datepicker();
                });</pre>
        </div>

        <hr>

        <h3 id="e4">Example 4 - Custom field types & validation</h3>
        <form method="post" action="#output">
            <textarea id="examplex" style="display: none;" name="myField"></textarea>
            <a href="#examplexcode" class="showcode button">Show Code</a>
            <a href="#" id="examplexconsole" class="button">Validate table</a>
        </form>

        <div id="examplexcode" style="display: none;" class="examplecode">

            <span class="title">script.js</span>
            <pre>
                /**
                * Example 4 - Custom field types & validation
                */
                var mynewtable = $('#examplex').editTable({
                field_templates: {
                'checkbox' : {
                html: '<input type="checkbox"/>',
                getValue: function (input) {
                return $(input).is(':checked');
                },
                setValue: function (input, value) {
                if ( value ){
                return $(input).attr('checked', true);
                }
                return $(input).removeAttr('checked');
                }
                },
                'textarea' : {
                html: '<textarea/>',
                getValue: function (input) {
                return $(input).val();
                },
                setValue: function (input, value) {
                return $(input).text(value);
                }
                },
                'select' : {
                html: '<select><option value="">None</option><option>All</option></select>',
                getValue: function (input) {
                return $(input).val();
                },
                setValue: function (input, value) {
                var select = $(input);
                select.find('option').filter(function() {
                return $(this).val() == value;
                }).attr('selected', true);
                return select;
                }
                }
                },
                row_template: ['checkbox', 'text', 'text', 'textarea', 'select'],
                headerCols: ['Yes/No','Date','Value','Description', 'Which?'],
                first_row: false,
                data: [
                [false,"01/30/2013","50,00 €","Lorem ipsum...\n\nDonec in dui nisl. Nam ac libero eget magna iaculis faucibus eu non arcu. Proin sed diam ut nisl scelerisque fermentum."],
                [true,"02/28/2013","50,00 €",'This is a <textarea>','All']
                ],

                // Checkbox validation
                validate_field: function (col_id, value, col_type, $element) {
                if ( col_type === 'checkbox' ) {
                $element.parent('td').animate({'background-color':'#fff'});
                if ( value === false ){
                $element.parent('td').animate({'background-color':'#DB4A39'});
                return false;
                }
                }
                return true;
                },
                tableClass: 'inputtable custom'
                });

                // Trigger event
                $('#examplexconsole').click(function(e) {

                // Get data
                console.log(mynewtable.getData());

                // Check if data are valid
                if ( !mynewtable.isValidated() ){
                alert('Not validated');
                }

                e.preventDefault();
                });
            </pre>

        </div>

        <hr>





    </div>

</body>
</html>


立即下载jquery.edittable.min.js查看所有js插件

网友评论0

程序员在线工具箱