JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="inputTA" name="inputTA" class="ta" rows="3" /></textarea>
<input type="Button" id="btn" value="Convert" />
CSS
.ta {
font: 8pt calibri;
background-color: whitesmoke;
border: 1px solid silver;
width: 350px;
height: 50px
}
.EmailAreaContainer {
background-color: lightgoldenrodyellow;
color: red
}
.EmailAreaTag {
background-color: slategray;
padding: 3px 3px 3px 7px;
border-radius: 5px;
color: white;
margin: 3px;
display: inline-block
}
.EmailAreaBtn {
color: white !important;
display: inline-block;
background-color: #b0b0b0;
width: 15px;
height: 15px;
border-radius: 10px;
text-align: center;
line-height: 15px;
margin-left: 5px;
cursor: pointer
}
JavaScript
$('#btn').click(function(){
emailArea($('#inputTA'), [',',';',' ']);
$(this).hide();
});
function emailArea(tao, sep) {
// Initialize globals
var validEmails = [],
invalidEmails = [],
ta, pta, eac, tc, tac, cn = 'EmailArea';
// Seperators
sep = sep || [',', ';', '\r', '\n', ' '];
// Add holder DIVs
ta = $('<div contentEditable="true" id="' + tao.attr('id') + '_' + cn + '"></div>');
tc = $('<div id="eaTags" />');
eac = $('<div id="eaContainer" />');
tao.after(eac);
eac.append(tc).append(ta);
// Attach after event handlers for keyup/press, paste
ta.on('keypress', function(e) {
// Look for comma, space, enter, semicolon as given in sep
var chr = String.fromCharCode(e.which);
if ($.inArray(chr, sep) >= 0) {
process(ta.text());
}
});
ta.on('paste', function() {
var text = $(this).text();
setTimeout(function() {
process(text);
}, 100);
});
// attach on focus for holder to ta
eac.on('click', function() {
ta.focus();
});
function process(str) {
// Clean str, replace separators with comma, remove space
$(sep).each(function() {
str = str.replace(new RegExp(this, "g"), ',').replace(/,+/g, ',')
});
// Split to array on comma or seperator parameter
// For each item in array see if valid email and add tag if yes
str.split(',').forEach(function(str) {
if (isValidEmail(str)) { // If valid, check if already added
if ($.inArray(str, validEmails) < 0) { // If not add a tag
addTag(str);
} else { // If yes, add new and remove old
removeTag(str);
addTag(str);
}
} else { // Add to invalid emails array
if ($.inArray(str, invalidEmails) < 0) {
invalidEmails.push(str);
...