Category Archive jQuery

Byphunsanit

jQuery: Ajax Cache

ต้องการเก็บข้อมูลส่วนที่ใช้บ่อยๆ ไว้ในฝั่ง user (browser) นั่นละ จะได้ลดการ query แต่ข้อมูลมันมีการเปลี่ยนแปลงด้วย ที่เก็บข้อมูลระยะยาวได้ในฝั่ง browser กลับออกแบบให้ localStorage เก็บข้อมูลถาวรโดยไม่มีการ expires เหมือน cookie ทำให้ต้องเขียน code จัดการเพิ่ม

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>Ajax: localStorage</title>
</head>

<body>
    <h1>localStorage</h1>
    <div class="col-sm-12" id="datasA"></div>
    <div class="col-sm-12" id="resultA"></div>
    <script src="../vendor/components/jquery/jquery.min.js"></script>
    <script>
        $(function() {

            function getDatas() {
                let cacheKey = 'memories';

                if (cacheKey in localStorage) {
                    let datas = JSON.parse(localStorage.getItem(cacheKey));

                    // if expired
                    if (datas['expires'] < Date.now()) {
                        localStorage.removeItem(cacheKey);

                        getDatas()
                    } else {
                        setDatas(datas);
                    }
                } else {
                    $.ajax({
                        "dataType": "json",
                        "success": function(datas, textStatus, jqXHR) {
                            let today = new Date();

                            datas['expires'] = today.setDate(today.getDate() + 7) // expires in next 7 days

                            setDatas(datas);

                            localStorage.setItem(cacheKey, JSON.stringify(datas));
                        },
                        "url": "http://localhost/phunsanit/snippets/PHP/json.json_encode.php",
                    });
                }
            }

            function setDatas(datas) {
                // display json as text
                $('#datasA').text(JSON.stringify(datas));

                // your code here
                let html = '';
                $.each(datas.datas, function(index, value) {
                    html += '<br>' + index + ' = ' + value;
                });
                $('#resultA').html(html);

            }

            // call
            getDatas();

        });
    </script>
</body>

</html>

ข้อมูลที่ call ผ่าน ajax จะโดนเก็บใน localStorage แต่เวลาใช้ก็จะเอามาเทียบ expires ก่อน ถ้ายังไม่หมดอายุก็เอามาใช้ ถ้าหมดอายุไปแล้วก็ call ใหม่ ลองดัดแปลงดูให้เหมาะกับงานดูครับ

Byphunsanit

javascript: string to JSON.parse()

หลังจากใช้ MySQL: return json format กันเป็นแล้วเรามาลองใช้กับ joget แทนที่จะต้องไปเขียน beanshell ให้ยุ่งยาก (พลาดง่ายๆ อีกตะหาก) ดูจริงๆ แล้วสามารถใช้กับหน้าเว็บทั้งหมดไม่ใช่แค่ joGet เพราะมันคือ javascript พื้นฐาน

เปิดฟอร์มที่ต้องการมา

  1. สร้าง section ขึ้นมา โดยกำหนด Load Binder เป็น JDBC Binder และ SQL SELECT Query ใส่ query ที่ต้องการ เช่น
    SELECT
        CONCAT('[',
                GROUP_CONCAT(JSON_OBJECT('label', name, 'value', appId)),
                ']') AS optionsList
    FROM
        jwdb.app_app
    ORDER BY name ASC
  2. ลาก Hidden Field มาตั้ง id เป็น optionsList ใน section ที่สร้างไว้
  3. เขียน javascript ดึงค่ามาจาก string json ที่เก็บไว้ใน input ชื่อ optionsList โดยใช้ JSON.parse() เผื่อความปลอดภัย ควรใช้ JSON.parse() ใน try catch เพราะว่าถ้า json ที่ได้ผิดปกติจะสามารถควบคุมได้ ลาก Custom HTML มาแล้วใส่ code
    <table class="table table-striped" id="tableA">
        <thead>
            <tr>
                <th scope="col" style="width:20px;">#</th>
                <th scope="col">Name</th>
                <th scope="col">Value</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <script>
        $(document).ready(function () {
    
            let html = new Array();
            let no = 0;
            let optionsList = $('#optionsList');
            try {
                let temp = JSON.parse(optionsList.val());
    
                if (temp.length > 0) {
                    $.each(temp, function (index, value) {
                        no++;
                        html.push('<tr><th scope="row">' + no + '</th><td>' + value.label + '</td><td>' + value.value + '</td><tr>');
                    });
                }
                if (html.length == 0) {
                    html = '<tr><th scope="row">-</th><td>-</td><td>-</td><tr>';
                } else {
                    html = html.join("\n");
                }
            } catch (e) {
                console.log(e.message);
                html = '<h1>Error!!</h1>';
            }
            $('#tableA > tbody').html(html);
    
        });
    </script>

สามารถ copy form ตัวอย่างได้จาก json

{
    "className": "org.joget.apps.form.model.Form",
    "properties": {
        "noPermissionMessage": "",
        "loadBinder": {
            "className": "org.joget.apps.form.lib.WorkflowFormBinder",
            "properties": {}
        },
        "name": "JSON Parse",
        "description": "",
        "postProcessorRunOn": "both",
        "permission": {
            "className": "",
            "properties": {}
        },
        "id": "JSONParse",
        "postProcessor": {
            "className": "",
            "properties": {}
        },
        "storeBinder": {
            "className": "org.joget.apps.form.lib.WorkflowFormBinder",
            "properties": {}
        },
        "tableName": "prototypes"
    },
    "elements": [
        {
            "elements": [
                {
                    "elements": [
                        {
                            "className": "org.joget.apps.form.lib.HiddenField",
                            "properties": {
                                "useDefaultWhenEmpty": "",
                                "workflowVariable": "",
                                "id": "optionsList",
                                "value": ""
                            }
                        }
                    ],
                    "className": "org.joget.apps.form.model.Column",
                    "properties": {
                        "width": "100%"
                    }
                }
            ],
            "className": "org.joget.apps.form.model.Section",
            "properties": {
                "readonly": "",
                "loadBinder": {
                    "className": "org.joget.plugin.enterprise.JdbcLoadBinder",
                    "properties": {
                        "jdbcDatasource": "default",
                        "sql": "SELECT \n    CONCAT('[',\n            GROUP_CONCAT(JSON_OBJECT('label', name, 'value', appId)),\n            ']') AS optionsList\nFROM\n    jwdb.app_app\nORDER BY name ASC"
                    }
                },
                "permissionReadonly": "",
                "permission": {
                    "className": "",
                    "properties": {}
                },
                "comment": "",
                "id": "section1",
                "label": "",
                "storeBinder": {
                    "className": "",
                    "properties": {}
                },
                "readonlyLabel": ""
            }
        },
        {
            "elements": [
                {
                    "elements": [
                        {
                            "className": "org.joget.apps.form.lib.CustomHTML",
                            "properties": {
                                "autoPopulate": "",
                                "id": "field2",
                                "label": "",
                                "value": "<table class=\"table table-striped\" id=\"tableA\">\n    <thead>\n        <tr>\n            <th scope=\"col\" style=\"width:20px;\">#</th>\n            <th scope=\"col\">Name</th>\n            <th scope=\"col\">Value</th>\n        </tr>\n    </thead>\n    <tbody>\n    </tbody>\n</table>\n<script>\n    $(document).ready(function () {\n\n        let html = new Array();\n        let no = 0;\n        let optionsList = $('#optionsList');\n        try {\n            let temp = JSON.parse(optionsList.val());\n\n            if (temp.length > 0) {\n                $.each(temp, function (index, value) {\n                    no++;\n                    html.push('<tr><th scope=\"row\">' + no + '</th><td>' + value.label + '</td><td>' + value.value + '</td><tr>');\n                });\n            }\n            if (html.length == 0) {\n                html = '<tr><th scope=\"row\">-</th><td>-</td><td>-</td><tr>';\n            } else {\n                html = html.join(\"\\n\");\n            }\n        } catch (e) {\n            console.log(e.message);\n            html = '<h1>Error!!</h1>';\n        }\n        $('#tableA > tbody').html(html);\n\n    });\n</script>"
                            }
                        }
                    ],
                    "className": "org.joget.apps.form.model.Column",
                    "properties": {
                        "width": "100%"
                    }
                }
            ],
            "className": "org.joget.apps.form.model.Section",
            "properties": {
                "readonly": "",
                "loadBinder": {
                    "className": "",
                    "properties": {}
                },
                "permissionReadonly": "",
                "permission": {
                    "className": "",
                    "properties": {}
                },
                "comment": "",
                "id": "section2",
                "label": "Options List",
                "storeBinder": {
                    "className": "",
                    "properties": {}
                },
                "readonlyLabel": ""
            }
        }
    ]
}

Byphunsanit

jQuery: เปลี่ยนลำดับ event

โดยปกติ event ของ jQuery จะทำงานตามลำดับที่มันโดน bind เอาไว้ ถ้าต้องการให้ทำบาง event ทำก่อน จะบอกว่า “ขอลุงก่อน” ไม่ได้ ต้องเขียนให้ bind ก่อน แต่ถ้าเป็น cms หรือเป็น code ที่โดยระบบใส่ให้เองก็ต้องใช้มาตรา 44 หรือลูกเล่นกันนิดหนึ่ง

คำถามนี้มีคนถามและตอบไว้ที่ jQuery event handlers always execute in order they were bound – any way around this? [duplicate] และเขียนตัวอย่างไว้ให้แล้ว http://jsfiddle.net/x8Na8/2/ งานก็เลยทำง่ายเลย ctrl+c ctrl+v เค้ามาแต่งให้หล่อหน่อยก็เอาไปใช้ได้เลย ขอขอบคุณคร๊าบบ

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>jQuery: Events Queue</title>
    <link href="../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>

<body>
    <h1>พร้อมเพย์ (PromptPay)</h1>
    <form action="values.php" class="form-horizontal" id="formA" method="post">
        <div class="form-group">
            <label class="col-sm-2 control-label">โอนเงินด้วย</label>
            <div class="col-sm-10">
                <div class="radio">
                    <label>
                        <input checked name="way" type="radio" value="socialid"> หมายเลขบัตรประชาชน
                    </label>
                </div>
                <div class="radio">
                    <label>
                        <input name="way" type="radio" value="phone"> หมายเลขโทรศัพท์
                    </label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label" for="socialidI">หมายเลขบัตรประชาชน</label>
            <div class="col-sm-10">
                <input class="form-control" id="socialidI" maxlength="13" name="socialid" placeholder="หมายเลขบัตรประชาชน" type="number">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label" for="phoneI">หมายเลขโทรศัพท์</label>
            <div class="col-sm-10">
                <input class="form-control" id="phoneI" maxlength="11" name="phone" placeholder="หมายเลขโทรศัพท์" type="tel">
            </div>
        </div>
        <div class="form-group">
            <label for="amount" class="col-sm-2 control-label">จำนวนเงิน</label>
            <div class="col-sm-10">
                <div class="input-group">
                    <input class="form-control" id="amount" max="5000" min="0" name="amount" placeholder="จำนวนเงิน" type="number">
                    <div class="input-group-addon">&#3647;</div>
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-10 text-right">
                <button type="submit" class="btn btn-success">โอนเงิน</button>
            </div>
        </div>
    </form>
    <div class="col-sm-12" id="resultA"></div>
    <script src="../vendor/components/jquery/jquery.min.js"></script>
    <script>
        $.fn.bindFirst = function (name, fn) {
            // bind as you normally would
            // don't want to miss out on any jQuery magic
            this.on(name, fn);

            // Thanks to a comment by @Martin, adding support for
            // namespaced events too.
            this.each(function () {
                var handlers = $._data(this, 'events')[name.split('.')[0]];
                // take out the handler we just inserted from the end
                var handler = handlers.pop();
                // move it at the beginning
                handlers.splice(0, 0, handler);
            });
        };
    </script>
    <script>
        $(function () {

            $('#formA').submit(function () {
                alert('1');
                return true;
            });

            $('#formA').submit(function () {
                alert('2');
                return true;
            });

            $('#formA').submit(function () {
                alert('3');
                return true;
            });

            $('#formA').bindFirst('submit', function () { alert('4'); });

        });
    </script>

</body>

</html>

Byphunsanit

Bootstrap: dynamic tabs hash

เพราะว่า dynamic tabs ของ Bootstrap มันจะไม่เลือก tabs จาก hash หรือเครื่องหมาย # ใน url ถ้าต้องการให้แสดงแท็บที่ต้องการจาก links ต้องเขียน code เพิ่มเติมอีกเล็กน้อย

<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>Bootstrap: Dynamic Tabs With Hash</title>
<link href="../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>

<body>
<div class="container">
<h2>Dynamic Tabs With Hash</h2>

<input id="tabindex" name="tabindex" type="text">

<ul class="nav nav-tabs">

<li class="nav-item">
<a class="active nav-link show" data-toggle="tab" href="#menu1">Menu 1</a>
</li>

<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#menu2">Menu 2</a>
</li>

<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#menu3">Menu 3</a>
</li>
</ul>

<div class="tab-content">

<div id="menu1" class="active fade in show tab-pane">
<h3>Menu 1</h3>
<p>นาย</p>
</div>

<div id="menu2" class="fade tab-pane">
<h3>Menu 2</h3>
<p>พิชญ์</p>
</div>

<div id="menu3" class="fade tab-pane">
<h3>Menu 3</h3>
<p>พันธุ์สนิท</p>
</div>

</div>

</div>

<script src="../vendor/components/jquery/jquery.min.js"></script>
<script src="../vendor/twbs/bootstrap/dist/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {

let hash = window.location.hash.substr(1);
let tabindex = $('#tabindex');
if (hash != tabindex.val()) {
$('a[href="#' + hash).click();
tabindex.val(hash);
}

});
</script>

</body>

</html>

เมื่อเปิดหน้าเว็บมาจาก url ที่ใส่ # ของแท็บที่ต้องการมา เช่น http://localhost/snippets/Bootstrap/tabs.dynamic.hash.html#menu2 แท็บก็จะเปิดหน้าที่ถูกต้องตามที่ต้องการ แทนที่จะดูจาก class active เพียงอย่าเดียว

Byphunsanit

Bootstrap: Dynamic Tabs

สามารถสร้างเนื้อหาที่เป็นรูปแบบ tabs หรือที่เรียกว่า dynamic tabs ได้โดยใช้แค่ jQuery และ Bootstrap

ตัวอย่าง

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>Bootstrap: Dynamic Tabs</title>
    <link href="../vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>

<body>
    <div class="container">
        <h2>Bootstrap: Dynamic Tabs</h2>

        <ul class="nav nav-tabs">

            <li class="nav-item">
                <a class="active nav-link show" data-toggle="tab" href="#menu1">Menu 1</a>
            </li>

            <li class="nav-item">
                <a class="nav-link" data-toggle="tab" href="#menu2">Menu 2</a>
            </li>

            <li class="nav-item">
                <a class="nav-link" data-toggle="tab" href="#menu3">Menu 3</a>
            </li>
        </ul>

        <div class="tab-content">

            <div id="menu1" class="active fade in show tab-pane">
                <h3>Menu 1</h3>
                <p>นาย</p>
            </div>

            <div id="menu2" class="fade tab-pane">
                <h3>Menu 2</h3>
                <p>พิชญ์</p>
            </div>

            <div id="menu3" class="fade tab-pane">
                <h3>Menu 3</h3>
                <p>พันธุ์สนิท</p>
            </div>

        </div>

    </div>

    <script src="../vendor/components/jquery/jquery.min.js"></script>
    <script src="../vendor/twbs/bootstrap/dist/js/bootstrap.min.js"></script>

</body>

</html>

โดยพื้นฐานคือใส่ data-toggle=”tab” ใน tag a ที่ลิงค์ไปยัง hash ที่เป็น id ของ div ที่มี class tab-pane ที่อยู่ใน div class tab-content ก็จะทำงานได้แล้วโดยไม่ต้องกำหนดสคริปเพิ่มเติมอีก แต่ถ้าหากต้องการเลือกแท็บจากลิงค์ให้อ่าน Bootstrap: dynamic tabs hash เพิ่มเติม