Skip to content

Instantly share code, notes, and snippets.

@twlca
Last active June 15, 2016 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twlca/6b198d61877a80ede8429a3707d25418 to your computer and use it in GitHub Desktop.
Save twlca/6b198d61877a80ede8429a3707d25418 to your computer and use it in GitHub Desktop.
Create Elements via JSON data
ct1 = document.getElementsByClassName('entry-content')[0];
function createElem( fm_name, tag, attrs, options ) {
if ( document.getElementsByName(fm_name).length != 0 ) {
var fm = document.getElementsByName(fm_name)[0];
} else {
var fm = document.createElement('form');
fm.setAttribute('name', fm_name);
ct1.appendChild(fm);
}
if ( tag && ['SELECT', 'TEXTAREA', 'INPUT'].indexOf( tag.toUpperCase()) >= 0 ) {
switch ( tag.toUpperCase()) {
case 'SELECT':
if ( attrs && attrs.name && options ) {
var lbl = document.createElement('label');
lbl.setAttribute('for', attrs.name);
lbl.innerText = attrs.name;
fm.appendChild(lbl);
var sel = document.createElement('select');
sel.setAttribute('name', attrs.name);
for (var i=0; i<options.length; i++) {
var opt = document.createElement('option');
opt.setAttribute('value', options[i].value);
opt.innerText = options[i].txt;
sel.appendChild(opt);
}
fm.appendChild(sel);
}
break;
case 'TEXTAREA':
if ( attrs && attrs.name ) {
var lbl = document.createElement('label');
lbl.setAttribute('for', attrs.name);
lbl.innerText = attrs.name;
var elem = document.createElement('textarea');
for ( var i in attrs ) {
elem.setAttribute( i, attrs[i] );
}
fm.appendChild(lbl);
fm.appendChild(elem);
} else {
console.log('Needs at least tag name');
}
break;
case 'INPUT':
if ( ['TXT', 'DATETIME', 'DATETIME-LOCAL', 'NUMBER', 'RANGE', 'PHONE', 'EMAIL', 'PASSWORD', 'COLOR', 'MONTH', 'SEARCH', 'TEL', 'TIME', 'URL', 'WEEK'].indexOf( attrs.type.toUpperCase()) >= 0 ) {
var lbl = document.createElement('label');
lbl.setAttribute('for', attrs.name);
lbl.innerText = attrs.name;
fm.appendChild(lbl);
var elem = document.createElement('input');
for (var i in attrs) {
elem.setAttribute(i, attrs[i]);
}
fm.appendChild(elem);
} else if ( ['RADIO', 'CHECKBOX'].indexOf( attrs.type.toUpperCase()) >= 0 ) {
var lbl = document.createElement('label');
lbl.setAttribute('for', attrs.name);
lbl.innerText = attrs.name;
fm.appendChild(lbl);
for (var i=0; i<options.length; i++) {
var elem = document.createElement('input');
for (var j in attrs) {
elem.setAttribute(j, attrs[j]);
elem.setAttribute('value', options[i].value);
}
var span = document.createElement('span');
span.innerText = options[i].txt;
fm.appendChild(elem);
fm.appendChild(span);
}
}
break;
}
} else {
console.log('Not appropriate tag');
}
}
@twlca
Copy link
Author

twlca commented Jun 14, 2016

未完成

  1. 本段程式僅適用於單一 form element,需置於迴圈中才能完成整個表單
  2. 然置於迴圈中,仍有待修改參數,使其適合置於 HTML 中的任何位置

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment