iT邦幫忙

2021 iThome 鐵人賽

1
Modern Web

JavaScript 從 50% 開始,打造函式庫不是問題!系列 第 43

JS 43 - 將表格式表單的資料列輸出為 JSON 格式

大家好!

今天要繼續昨天的表格式表單,將新增的資料列輸出為 JSON 格式。
我們進入今天的主題吧!


樣式

.caption {
    display: table-caption;
}

程式碼

const trs = Felix('.tr');
const textarea = Felix('#result textarea');

form.on('submit', output);

function output(e) {
    e.preventDefault();

    const obj = {};
    const ids = [].map.call(inputs, (input) => input.id);

    Felix.forEach(trs, function (tr) {
        let i = 1;
        const children = tr.children;
        const key = obj[children[0][0].value] = {};

        Felix.forEach([].slice.call(children, 1, -1), function (td) {
            key[i++] = td[0].value;
        });
    });
    
    textarea[0].textContent = JSON.stringify(obj);
}

實測

<body>
    <form class="table">
        <!-- ... -->
        <div class="caption">
            <input type="submit" value="Output as JSON Format">
        </div>
    </form>
    <div id="result">
        <textarea readonly></textarea>
    </div>
</body>

範例連結製作中。


差不多也到尾聲了。
如果對文章有任何疑問,也歡迎在下方提問和建議!
我是 Felix,我們明天再見!


上一篇
JS 42 - 新增或刪除表格式表單的資料列
下一篇
JS 44 - 輸入網址就能使用的 RSS 閱讀器
系列文
JavaScript 從 50% 開始,打造函式庫不是問題!46
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言