

將 Word 內容直接轉成 GIGO 網頁輸入介面
source link: https://blog.darkthread.net/blog/gigo-fields/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

系統有張表單包含一個使用者自訂區塊,允許業務單位放入備註性質資料讓使用者填寫,該備註只對承辦人員有意義,與作業程序完全無關,且各單位所而內容不同,偶爾會調整。思考了一下,我打算將其視為黑盒子不解析內容,採 Garbage In Garbage Out 策略,是較省時省力的做法。但有個問題 - 備註內容有的會包簡單選取方塊或文字空格讓使用者勾選填寫,也非全然是唯護資訊,即有互動操作要求,還能做到 GIGO 嗎?嗯,程式老魔人被這種小需求難倒像話嗎?來試試吧!
使用者慣用的資訊形式如下:
有選項可勾選(方格塗黑),底線處可填寫文字,這是 Word 設計問卷常用的經典做法,大家應該不陌生。因此,若我有辦法將它直接轉換成可填寫的網頁介面,未來還能用在其他地方。
我的概念是寫一小段程式,直接將純文字轉為可輸入欄位,姑且命名為 GIGO (Garbage In Garbage Out) 欄位。因應 IE 在企業內最多還能再戰七年,網頁要支援 IE。
最後成品效果如下,應用時將 Word 內容轉為純文字,以 <pre> 方式在網頁呈現,維持原有換行及排版,。下【轉為GIGO欄位】時程式將文字裡的方格符號轉為點擊會切換塗黑及空格的 <span>,連續四根底線則轉為 <input>,靜態文字搖身一變轉成網頁輸入介面;輸入完畢,按下【讀取填寫結果】,輸入結果會再轉回純文字,但勾選項目的方格符號會換成實心方塊符號,輸入文字也會以 __輸入內容__
方式呈現,前後保留兩根底線是為了識別這段範圍為可輸欄位。
使用者填寫轉成的純文字結果視為 <textarea> 填寫內容送到伺服器,不做解析及檢核(要做也可以,把它當成來自 <textarea> 的值就對了),存入 XML、JSON 或資料庫,是謂 Garbage In Garbage Out。基本上把它想成 <textarea> 就對了,一個能勾選跟限定文字輸入位置的 <textarea>。
很巧妙吧?至少我覺得很輕巧簡便,而程式也算簡潔,不到 30 行搞定:線上展示
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<pre id='fldWord'>
□ 雞排 □ 珍奶 □ 臭豆腐
□ 蛋塔 □ 可樂
□ 其它 ____(開放填寫)
</pre>
<div>
<button id="btnToWordField">轉為GIGO欄位</button>
<button id="btnToText">讀取填寫結果</button>
</div>
<pre></pre>
<style>
span.wf-cbx {
display: inline-block; cursor: pointer;
width: 1em; height: 1em;
border: 1px solid #444;
}
span.wf-cbx.wf-chked {
background-color: black;
}
.wf-field input { margin: 0 3px; }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).on('click', '.wf-field span.wf-cbx', function() {
$(this).toggleClass('wf-chked');
});
function convToWordField(selector) {
var f = $(selector);
var t = f.text();
t = t.replace(/□/g, '<span class=wf-cbx></span>');
t = t.replace(/■/g, '<span class="wf-cbx wf-chked"></span>');
t = t.replace(/__([^_]*)__/g, '<input value="$1" />');
f.html(t).addClass('wf-field');
}
function readWordField(selector) {
var f = $(selector);
f.find(".wf-cbx").each(function() {
var e = $(this);
e.text(e.hasClass('wf-chked') ? '■' : '□').attr('class', null);
});
f.find('input').each(function() {
var e = $(this);
var t = '__' + e.val() + '__';
e.after('<span>' + t + '</span>');
e.remove();
});
var h = f.html();
h = h.replace(/<[/]*span>/g, '');
f.text(h);
}
$('#btnToWordField').click(function() {
convToWordField('#fldWord');
});
$('#btnToText').click(function() {
readWordField('#fldWord');
});
</script>
</body>
</html>
近期自覺得意的作品 + 1,不免俗野人獻曝一下囉。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK