JSFiddle - React, Tailwind, and code Playground
by Ting-Yuan Chang
HTML
Input box
<div id="inputBox" contenteditable="true">ABC<br>DEF<br>* 123<br>* 456<br>GHI</div>
<br/>
Output box
<div id="outputBox" class="outputBox"></div>
<br/>
Output HTML
<pre id="showHTML"></pre>
<br/>
translated Box
<div id="translatedBox" class="outputBox"></div>
<br/>
translated HTML
<pre id="translatedHTML"></pre>
CSS
div{
background: #eee;
padding:10px;
}
pre{
white-space: pre-wrap;
background: #000;
color:#fff;
padding:10px;
}
JavaScript
function update() {
var str = $('#inputBox').html();
$('#outputBox').html(str);
$('#showHTML').text(str);
str = str.replace(/(<br>$)/,'')
.replace(/(<br>)/g,'$1\n')
.replace(/\* (.*)/g, '<li>$1</li>')
.replace(/^(?!<li>)/gm,'<input type="checkbox" name="field_1" value="on">')
.replace(/^<li>(.*)<\/li>/gm,'<li><input type="checkbox" name="field_1" value="on">$1</li>');
if(str.indexOf('<li>')!=-1) {
var index = str.indexOf('<li>');
var lastIndex;
str = str.substring(0, index) + '<ul>' + str.substring(index);
lastIndex = str.lastIndexOf('</li>') + '</li>'.length+ 1;
str = str.substring(0, lastIndex) + '</ul>' + str.substring(lastIndex);
}
$('#translatedBox').html(str);
$('#translatedHTML').text(str);
}
$('#inputBox').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode == 13) {
document.execCommand('insertHTML', false, '<br>');
$('.outputBox').html($(this).html());
//document.execCommand('insertBrOnReturn', false, true);
// prevent the default behaviour of return key pressed
return false;
}
});
$('#inputBox').keyup(function(e) {
update();
});
$('#checkbox').click(function() {
var $p = "";
var re = /\S/;
$p = $('.outputBox');
$p.contents()
.filter(function() {
return this.nodeType == 3&& re.test(this.nodeValue);
})
.wrap('<label> <input type="checkbox" name="field_1" value="on" />');
});
update();