I have a problem while using this (enter multiple emails in an input) that I got from here https://github.com/pierresh/multiple-emails.js/tree/master
the problem is that when I enter a placeholder text onto the input field, it appears for a few second then disappears, I have tried finding out the problems in the js and css file but I still failed to find what causes the placeholder text to disappear.
I tried added this code at a lot of place but the text still disappears
$("#emailInviteList").attr("placeholder", "Friend's email").blur();
this is the multiple-emails.js
(function( $ ){
$.fn.multiple_emails = function(options) {
// Default options
var defaults = {
checkDupEmail: true,
theme: "Bootstrap",
position: "top"
};
// Merge send options with defaults
var settings = $.extend( {}, defaults, options );
var deleteIconHTML = "";
if (settings.theme.toLowerCase() == "Bootstrap".toLowerCase())
{
deleteIconHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
else if (settings.theme.toLowerCase() == "SemanticUI".toLowerCase() || settings.theme.toLowerCase() == "Semantic-UI".toLowerCase() || settings.theme.toLowerCase() == "Semantic UI".toLowerCase()) {
deleteIconHTML = '<i class="remove icon"></i>';
}
else if (settings.theme.toLowerCase() == "Basic".toLowerCase()) {
//Default which you should use if you don't use Bootstrap, SemanticUI, or other CSS frameworks
deleteIconHTML = '<i class="basicdeleteicon">Remove</i>';
}
return this.each(function() {
//$orig refers to the input HTML node
var $orig = $(this);
var $list = $('<ul class="multiple_emails-ul" />'); // create html elements - list of email addresses as unordered list
if ($(this).val() != '' && IsJsonString($(this).val())) {
$.each(jQuery.parseJSON($(this).val()), function( index, val ) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + val.toLowerCase() + '">' + val + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
});
}
var $input = $('<input type="text" class="multiple_emails-input text-left" />').on('keyup', function(e) { // input
$(this).removeClass('multiple_emails-error');
var input_length = $(this).val().length;
var keynum;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
//if(event.which == 8 && input_length == 0) { $list.find('li').last().remove(); } //Removes last item on backspace with no input
// Supported key press is tab, enter, space or comma, there is no support for semi-colon since the keyCode differs in various browsers
if(keynum == 9 || keynum == 32 || keynum == 188) {
display_email($(this), settings.checkDupEmail);
}
else if (keynum == 13) {
display_email($(this), settings.checkDupEmail);
//Prevents enter key default
//This is to prevent the form from submitting with the submit button
//when you press enter in the email textbox
e.preventDefault();
}
}).on('blur', function(event){
if ($(this).val() != '') { display_email($(this), settings.checkDupEmail); }
});
var $container = $('<div class="multiple_emails-container" />').click(function() { $input.focus(); } ); // container div
// insert elements into DOM
if (settings.position.toLowerCase() === "top")
$container.append($list).append($input).insertAfter($(this));
else
$container.append($input).append($list).insertBefore($(this));
/*
t is the text input device.
Value of the input could be a long line of copy-pasted emails, not just a single email.
As such, the string is tokenized, with each token validated individually.
If the dupEmailCheck variable is set to true, scans for duplicate emails, and invalidates input if found.
Otherwise allows emails to have duplicated values if false.
*/
function display_email(t, dupEmailCheck) {
//Remove space, comma and semi-colon from beginning and end of string
//Does not remove inside the string as the email will need to be tokenized using space, comma and semi-colon
var arr = t.val().trim().replace(/^,|,$/g , '').replace(/^;|;$/g , '');
//Remove the double quote
arr = arr.replace(/"/g,"");
//Split the string into an array, with the space, comma, and semi-colon as the separator
arr = arr.split(/[\s,;]+/);
var errorEmails = new Array(); //New array to contain the errors
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
for (var i = 0; i < arr.length; i++) {
//Check if the email is already added, only if dupEmailCheck is set to true
if ( dupEmailCheck === true && $orig.val().indexOf(arr[i]) != -1 ) {
if (arr[i] && arr[i].length > 0) {
new function () {
var existingElement = $list.find('.email_name[data-email=' + arr[i].toLowerCase().replace('.', '\\.').replace('#', '\\#') + ']');
existingElement.css('font-weight', 'bold');
setTimeout(function() { existingElement.css('font-weight', ''); }, 1500);
}(); // Use a IIFE function to create a new scope so existingElement won't be overriden
}
}
else if (pattern.test(arr[i]) == true) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + arr[i].toLowerCase() + '">' + arr[i] + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
}
else
errorEmails.push(arr[i]);
}
// If erroneous emails found, or if duplicate email found
if(errorEmails.length > 0)
t.val(errorEmails.join("; ")).addClass('multiple_emails-error');
else
t.val("");
refresh_emails ();
}
function refresh_emails () {
var emails = new Array();
var container = $orig.siblings('.multiple_emails-container');
container.find('.multiple_emails-email span.email_name').each(function() { emails.push($(this).html()); });
$orig.val(JSON.stringify(emails)).trigger('change');
}
function IsJsonString(str) {
try { JSON.parse(str); }
catch (e) { return false; }
return true;
}
return $(this).hide();
});
};
})(jQuery);
this is the multiple-emails.css
.multiple_emails-container {
border:1px #ccc solid;
border-radius: 4px;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
padding:0; margin: 0; cursor:text; width:100%;
padding-top: 5px;
background-color: white;
}
.multiple_emails-container input {
clear:both;
width:100%;
height: 30px;
text-align: center;
border:0;
outline: none;
margin-bottom:3px;
padding-left: 5px;
box-sizing: border-box;
}
.multiple_emails-container input{
border: 0 !important;
}
.multiple_emails-container input.multiple_emails-error {
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px red !important;
outline: thin auto red !important;
}
.multiple_emails-container ul {
list-style-type:none;
padding-left: 0;
}
.multiple_emails-email {
margin: 3px 5px 3px 5px;
padding: 3px 5px 3px 5px;
border:1px #BBD8FB solid;
border-radius: 3px;
background: #F3F7FD;
}
.multiple_emails-close {
float:left;
margin:0 3px;
}
this is part of my code in the html file
<script type="text/javascript">
$(function() {
$('#emailInviteList').multiple_emails({position: "bottom"});
});
</script>
<div class='form-group'>
<input type='email' id='emailInviteList' name='emailInviteList' class="form-control" placeholder="Friend's Email">
</div>
Script is creating another textfield which does not have placeholder attribute, below is updated snippet I have just added placeholder="Friend\'s Email" in input var $input.
(function( $ ){
$.fn.multiple_emails = function(options) {
// Default options
var defaults = {
checkDupEmail: true,
theme: "Bootstrap",
position: "top"
};
// Merge send options with defaults
var settings = $.extend( {}, defaults, options );
var deleteIconHTML = "";
if (settings.theme.toLowerCase() == "Bootstrap".toLowerCase())
{
deleteIconHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
else if (settings.theme.toLowerCase() == "SemanticUI".toLowerCase() || settings.theme.toLowerCase() == "Semantic-UI".toLowerCase() || settings.theme.toLowerCase() == "Semantic UI".toLowerCase()) {
deleteIconHTML = '<i class="remove icon"></i>';
}
else if (settings.theme.toLowerCase() == "Basic".toLowerCase()) {
//Default which you should use if you don't use Bootstrap, SemanticUI, or other CSS frameworks
deleteIconHTML = '<i class="basicdeleteicon">Remove</i>';
}
return this.each(function() {
//$orig refers to the input HTML node
var $orig = $(this);
var $list = $('<ul class="multiple_emails-ul" />'); // create html elements - list of email addresses as unordered list
if ($(this).val() != '' && IsJsonString($(this).val())) {
$.each(jQuery.parseJSON($(this).val()), function( index, val ) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + val.toLowerCase() + '">' + val + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
});
}
var $input = $('<input type="text" class="multiple_emails-input text-left" placeholder="Friend\'s Email" />').on('keyup', function(e) { // input
$(this).removeClass('multiple_emails-error');
var input_length = $(this).val().length;
var keynum;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
//if(event.which == 8 && input_length == 0) { $list.find('li').last().remove(); } //Removes last item on backspace with no input
// Supported key press is tab, enter, space or comma, there is no support for semi-colon since the keyCode differs in various browsers
if(keynum == 9 || keynum == 32 || keynum == 188) {
display_email($(this), settings.checkDupEmail);
}
else if (keynum == 13) {
display_email($(this), settings.checkDupEmail);
//Prevents enter key default
//This is to prevent the form from submitting with the submit button
//when you press enter in the email textbox
e.preventDefault();
}
}).on('blur', function(event){
if ($(this).val() != '') { display_email($(this), settings.checkDupEmail); }
});
var $container = $('<div class="multiple_emails-container" />').click(function() { $input.focus(); } ); // container div
// insert elements into DOM
if (settings.position.toLowerCase() === "top")
$container.append($list).append($input).insertAfter($(this));
else
$container.append($input).append($list).insertBefore($(this));
/*
t is the text input device.
Value of the input could be a long line of copy-pasted emails, not just a single email.
As such, the string is tokenized, with each token validated individually.
If the dupEmailCheck variable is set to true, scans for duplicate emails, and invalidates input if found.
Otherwise allows emails to have duplicated values if false.
*/
function display_email(t, dupEmailCheck) {
//Remove space, comma and semi-colon from beginning and end of string
//Does not remove inside the string as the email will need to be tokenized using space, comma and semi-colon
var arr = t.val().trim().replace(/^,|,$/g , '').replace(/^;|;$/g , '');
//Remove the double quote
arr = arr.replace(/"/g,"");
//Split the string into an array, with the space, comma, and semi-colon as the separator
arr = arr.split(/[\s,;]+/);
var errorEmails = new Array(); //New array to contain the errors
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
for (var i = 0; i < arr.length; i++) {
//Check if the email is already added, only if dupEmailCheck is set to true
if ( dupEmailCheck === true && $orig.val().indexOf(arr[i]) != -1 ) {
if (arr[i] && arr[i].length > 0) {
new function () {
var existingElement = $list.find('.email_name[data-email=' + arr[i].toLowerCase().replace('.', '\\.').replace('#', '\\#') + ']');
existingElement.css('font-weight', 'bold');
setTimeout(function() { existingElement.css('font-weight', ''); }, 1500);
}(); // Use a IIFE function to create a new scope so existingElement won't be overriden
}
}
else if (pattern.test(arr[i]) == true) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + arr[i].toLowerCase() + '">' + arr[i] + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
}
else
errorEmails.push(arr[i]);
}
// If erroneous emails found, or if duplicate email found
if(errorEmails.length > 0)
t.val(errorEmails.join("; ")).addClass('multiple_emails-error');
else
t.val("");
refresh_emails ();
}
function refresh_emails () {
var emails = new Array();
var container = $orig.siblings('.multiple_emails-container');
container.find('.multiple_emails-email span.email_name').each(function() { emails.push($(this).html()); });
$orig.val(JSON.stringify(emails)).trigger('change');
}
function IsJsonString(str) {
try { JSON.parse(str); }
catch (e) { return false; }
return true;
}
return $(this).hide();
});
};
})(jQuery);
.multiple_emails-container {
border:1px #ccc solid;
border-radius: 4px;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
padding:0; margin: 0; cursor:text; width:100%;
padding-top: 5px;
background-color: white;
}
.multiple_emails-container input {
clear:both;
width:100%;
height: 30px;
text-align: center;
border:0;
outline: none;
margin-bottom:3px;
padding-left: 5px;
box-sizing: border-box;
}
.multiple_emails-container input{
border: 0 !important;
}
.multiple_emails-container input.multiple_emails-error {
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px red !important;
outline: thin auto red !important;
}
.multiple_emails-container ul {
list-style-type:none;
padding-left: 0;
}
.multiple_emails-email {
margin: 3px 5px 3px 5px;
padding: 3px 5px 3px 5px;
border:1px #BBD8FB solid;
border-radius: 3px;
background: #F3F7FD;
}
.multiple_emails-close {
float:left;
margin:0 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#emailInviteList').multiple_emails({position: "bottom"});
});
</script>
<div class='form-group'>
<input type='email' id='emailInviteList' name='emailInviteList' class="form-control" placeholder="Friend's Email">
</div>
Related
I have created a drop down menu with checkbox options. The idea is when user select one or more checkboxes, the checked value should be passed to an SQL statement in a php page through AJAX. However, my sql does not seem to generate the result as it should be. My SQL statement is using an IN operator where the checked value should be inside the WHERE clause. For example, if I select CONSTRUCTION, HCL and RSS from the drop the menu checkboxes, the SQL statement in the php page should be SELECT * FROM STAFF WHERE SERVICE IN ('CONSTRUCTION', 'HCL', 'RSS'). However, when i echo my SQL statement, it was showing the checked values without the single quote - SELECT * FROM STAFF WHERE SERVICE IN (CONSTRUCTION, HCL, RS)which is incorrect. How can i include the single quotes for each checked values from the drop down for the IN operator? Can anyone help?
Below is my PHP and the drop down menu
sql.php
<?php
if($_POST['dataarray'] != ""){
$sql = "SELECT * FROM STAFF WHERE SERVICE IN (".$_POST['dataarray'].")";
.....
...
/*************SQL output*********************/
}
?>
Drop Down Menu with checkboxes
$(document).ready(function(){
/*********************convert select into multiselect************************/
$("#service").CreateMultiCheckBox({ width: '300px', defaultText : 'Select Below', height:'auto' });
$("#service").on('change', function (){
var dataarray = [];
$("#service option").each(function(){
if($(this).is(":checked"))
{dataarray.push($(this).val());}
});
dataarray = dataarray.toString();
$.ajax({
url: "sql.php",
method:"POST",
data: {dataarray:dataarrayy},
success: function(data){
}
});
});
/**********************creating of checkboxes for each select option************************/
$(document).on("click", ".MultiCheckBox", function () {
var detail = $(this).next();
detail.show();
});
$(document).on("click", ".MultiCheckBoxDetailHeader input", function (e) {
e.stopPropagation();
var hc = $(this).prop("checked");
$(this).closest(".MultiCheckBoxDetail").find(".MultiCheckBoxDetailBody input").prop("checked", hc);
$(this).closest(".MultiCheckBoxDetail").next().UpdateSelect();
});
$(document).on("click", ".MultiCheckBoxDetailHeader", function (e) {
var inp = $(this).find("input");
var chk = inp.prop("checked");
inp.prop("checked", !chk);
$(this).closest(".MultiCheckBoxDetail").find(".MultiCheckBoxDetailBody input").prop("checked", !chk);
$(this).closest(".MultiCheckBoxDetail").next().UpdateSelect();
});
$(document).on("click", ".MultiCheckBoxDetail .cont input", function (e) {
e.stopPropagation();
$(this).closest(".MultiCheckBoxDetail").next().UpdateSelect();
var val = ($(".MultiCheckBoxDetailBody input:checked").length == $(".MultiCheckBoxDetailBody input").length)
$(".MultiCheckBoxDetailHeader input").prop("checked", val);
});
$(document).on("click", ".MultiCheckBoxDetail .cont", function (e) {
var inp = $(this).find("input");
var chk = inp.prop("checked");
inp.prop("checked", !chk);
var multiCheckBoxDetail = $(this).closest(".MultiCheckBoxDetail");
var multiCheckBoxDetailBody = $(this).closest(".MultiCheckBoxDetailBody");
multiCheckBoxDetail.next().UpdateSelect();
var val = ($(".MultiCheckBoxDetailBody input:checked").length == $(".MultiCheckBoxDetailBody input").length)
$(".MultiCheckBoxDetailHeader input").prop("checked", val);
});
$(document).mouseup(function (e) {
var container = $(".MultiCheckBoxDetail");
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.hide();
}
});
});
var defaultMultiCheckBoxOption = { width: '220px', defaultText: 'Select Below', height: '200px' };
jQuery.fn.extend({
CreateMultiCheckBox: function (options) {
var localOption = {};
localOption.width = (options != null && options.width != null && options.width != undefined) ? options.width : defaultMultiCheckBoxOption.width;
localOption.defaultText = (options != null && options.defaultText != null && options.defaultText != undefined) ? options.defaultText : defaultMultiCheckBoxOption.defaultText;
localOption.height = (options != null && options.height != null && options.height != undefined) ? options.height : defaultMultiCheckBoxOption.height;
this.hide();
this.attr("multiple", "multiple");
var divSel = $("<div class='MultiCheckBox'>" + localOption.defaultText + "<span class='k-icon k-i-arrow-60-down'><svg aria-hidden='true' focusable='false' data-prefix='fas' data-icon='sort-down' role='img' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512' class='svg-inline--fa fa-sort-down fa-w-10 fa-2x'><path fill='currentColor' d='M41 288h238c21.4 0 32.1 25.9 17 41L177 448c-9.4 9.4-24.6 9.4-33.9 0L24 329c-15.1-15.1-4.4-41 17-41z' class=''></path></svg></span></div>").insertBefore(this);
divSel.css({ "width": localOption.width });
var detail = $("<div class='MultiCheckBoxDetail'><div class='MultiCheckBoxDetailHeader'><input type='checkbox' class='mulinput' value='-1982' /><div>Select All</div></div><div class='MultiCheckBoxDetailBody'></div></div>").insertAfter(divSel);
detail.css({ "width": parseInt(options.width) + 10, "max-height": localOption.height });
var multiCheckBoxDetailBody = detail.find(".MultiCheckBoxDetailBody");
this.find("option").each(function () {
var val = $(this).attr("value");
if (val == undefined)
val = '';
multiCheckBoxDetailBody.append("<div class='cont'><div><input type='checkbox' class='mulinput' value='" + val + "' /></div><div>" + $(this).text() + "</div></div>");
});
multiCheckBoxDetailBody.css("max-height", (parseInt($(".MultiCheckBoxDetail").css("max-height")) - 28) + "px");
},
UpdateSelect: function () {
var arr = [];
this.prev().find(".mulinput:checked").each(function () {
arr.push($(this).val());
});
this.val(arr).change();
},
});
.MultiCheckBox {
border:1px solid #e2e2e2;
padding: 5px;
border-radius:4px;
cursor:pointer;
background:#ffffff;
}
.MultiCheckBox .k-icon{
font-size: 15px;
float: right;
font-weight: bolder;
margin-top: -7px;
height: 10px;
width: 14px;
color:#787878;
}
.MultiCheckBoxDetail {
display:none;
position:absolute;
border:1px solid #e2e2e2;
overflow-y:hidden;
background:#ffffff;
}
.MultiCheckBoxDetailBody {
overflow-y:scroll;
}
.MultiCheckBoxDetail .cont {
clear:both;
overflow: hidden;
padding: 2px;
}
.MultiCheckBoxDetail .cont:hover {
background-color:#cfcfcf;
}
.MultiCheckBoxDetailBody > div > div {
float:left;
}
.MultiCheckBoxDetail>div>div:nth-child(1) {
}
.MultiCheckBoxDetailHeader {
overflow:hidden;
position:relative;
height: 28px;
background-color:#3d3d3d;
}
.MultiCheckBoxDetailHeader>input {
position: absolute;
top: 4px;
left: 3px;
}
.MultiCheckBoxDetailHeader>div {
position: absolute;
top: 5px;
left: 24px;
color:#fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<select name="service" class="service" id="service">
<option value="CONSTRUCTION">Construction</option>
<option value="HCL">HCL</option>
<option value="MANUFACTURING">Manufacturing</option>
<option value="MYE">MYE</option>
<option value="RSS">RSS</option>
<option value="SERVICE">SERVICE</option>
<option value="NA">NA</option>
</select>
What you are doing there is very risky. You are putting the $_POST input directly into your sql-Query. This can lead to serious mysql-injections issues.
You should sanitize your $_POST data first. For instance use Methods like
stripslashes to remove unwanted characters that can lead to sql-injections.
Or use a database wrapper that uses prepared statements like Pdo
To answer your String related question:
You can iterate over your data array and wrap the string with quotes:
E.g.
$dataArray = [];
foreach ($_POST['dataarray'] as $item) {
$dataArray[] = "'" . $item . "'";
}
$sql = "SELECT * FROM STAFF WHERE SERVICE IN (". implode(', ', $dataArray) .")";
I am passing a very very hard time with JavaScript and I have zero knowledge with jQuery. I am trying to highlight a text from a page or from a body with the help of JavaScript and jQuery.
With hard try, I manage a search code with highlight.
My HTML code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="/javascripts/application.js" type="text/javascript">
</head>
<body>
Search: <input type="text" id="text-search" />
<p>
<b>Demo </b> he new edition of KnowlEdge K12 enables your school with flexibility by wholly automating their administrative and academic processes. With IncTech’s solution for K12 schools, you can. We give you an internal infrastructure so you can share school and student information.
</p>
</body>
My full code with jQuery and JavaScript:
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && !/(script|style) /i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.each(function() {
innerHighlight(this, pat.toUpperCase());
});
};
jQuery.fn.removeHighlight = function() {
function newNormalize(node) {
for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
var child = children[i];
if (child.nodeType == 1) {
newNormalize(child);
continue;
}
if (child.nodeType != 3) { continue; }
var next = child.nextSibling;
if (next == null || next.nodeType != 3) { continue; }
var combined_text = child.nodeValue + next.nodeValue;
new_node = node.ownerDocument.createTextNode(combined_text);
node.insertBefore(new_node, child);
node.removeChild(child);
node.removeChild(next);
i--;
nodeCount--;
}
}
return this.find("span.highlight").each(function() {
var thisParent = this.parentNode;
thisParent.replaceChild(this.firstChild, this);
newNormalize(thisParent);
}).end();
};
$(function() {
$('#text-search').bind('keyup change', function(ev) {
// pull in the new value
var searchTerm = $(this).val();
// remove any old highlighted terms
$('body').removeHighlight();
// disable highlighting if empty
if ( searchTerm ) {
// highlight the new term
$('body').highlight( searchTerm );
}
});
});
.highlight {
background-color: #fff34d;
-moz-border-radius: 5px; /* FF1+ */
-webkit-border-radius: 5px; /* Saf3-4 */
border-radius: 5px; /* Opera 10.5, IE 9, Saf5, Chrome */
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* FF3.5+ */
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Saf3.0+, Chrome */
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Opera 10.5+, IE 9.0 */
}
.highlight {
padding:1px 4px;
margin:0 -4px;
}
Please don't ask me for any kind of more info. Every thing is given in comment section. Guys please please help me.
The only issue i could see in your example is in this line
<script src="/javascripts/application.js" type="text/javascript">
which is looking for this .js and not founding it due to this highlight functions are not getting created.
Try changing it with this and add application.js with different script tag.
<script type="text/javascript">
Working Example
.highlight {
background-color: #fff34d;
-moz-border-radius: 5px; /* FF1+ */
-webkit-border-radius: 5px; /* Saf3-4 */
border-radius: 5px; /* Opera 10.5, IE 9, Saf5, Chrome */
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* FF3.5+ */
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Saf3.0+, Chrome */
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Opera 10.5+, IE 9.0 */
}
.highlight {
padding:1px 4px;
margin:0 -4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && !/(script|style) /i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.each(function() {
innerHighlight(this, pat.toUpperCase());
});
};
jQuery.fn.removeHighlight = function() {
function newNormalize(node) {
for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
var child = children[i];
if (child.nodeType == 1) {
newNormalize(child);
continue;
}
if (child.nodeType != 3) { continue; }
var next = child.nextSibling;
if (next == null || next.nodeType != 3) { continue; }
var combined_text = child.nodeValue + next.nodeValue;
new_node = node.ownerDocument.createTextNode(combined_text);
node.insertBefore(new_node, child);
node.removeChild(child);
node.removeChild(next);
i--;
nodeCount--;
}
}
return this.find("span.highlight").each(function() {
var thisParent = this.parentNode;
thisParent.replaceChild(this.firstChild, this);
newNormalize(thisParent);
}).end();
};
</script>
<body>
Search: <input type="text" id="text-search" />
<p>
<b>Demo </b> he new edition of KnowlEdge K12 enables your school with flexibility by wholly automating their administrative and academic processes. With IncTech’s solution for K12 schools, you can. We give you an internal infrastructure so you can share school and student information.
</p>
<script type="text/javascript">
$(function() {
$('#text-search').bind('keyup change', function(ev) {
// pull in the new value
var searchTerm = $(this).val();
// remove any old highlighted terms
$('body').removeHighlight();
// disable highlighting if empty
if ( searchTerm ) {
// highlight the new term
$('body').highlight( searchTerm );
}
});
});
</script>
</body>
The following code converts text into equal paragraphs, based on the users input character amount.
Is it possible for the input box to calculate the amount of words for each paragraph instead of being based on the character amount?
JSFiddle
If an updated fiddle could please be provided, would be much appreciated, as I am still new to coding.
Thank You!
$(function() {
$('select').on('change', function() {
//Lets target the parent element, instead of P. P will inherit it's font size (css)
var targets = $('#content'),
property = this.dataset.property;
targets.css(property, this.value);
sameheight('#content p');
}).prop('selectedIndex', 0);
});
var btn = document.getElementById('go'),
textarea = document.getElementById('textarea1'),
content = document.getElementById('content');
chunkSize = 100;
btn.addEventListener('click', initialDistribute);
content.addEventListener('keyup', handleKey);
content.addEventListener('paste', handlePaste);
function initialDistribute() {
custom = parseInt(document.getElementById("custom").value);
chunkSize = (custom>0)?custom:chunkSize;
var text = textarea.value;
while (content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
rearrange(text);
}
function rearrange(text) {
var chunks = splitText(text, false);
chunks.forEach(function(str, idx) {
para = document.createElement('P');
para.classList.add("Paragraph_CSS");
para.setAttribute('contenteditable', true);
para.textContent = str;
content.appendChild(para);
});
sameheight('#content p');
}
function handleKey(e) {
var para = e.target,
position,
key, fragment, overflow, remainingText;
key = e.which || e.keyCode || 0;
if (para.tagName != 'P') {
return;
}
if (key != 13 && key != 8) {
redistributeAuto(para);
return;
}
position = window.getSelection().getRangeAt(0).startOffset;
if (key == 13) {
fragment = para.lastChild;
overflow = fragment.textContent;
fragment.parentNode.removeChild(fragment);
remainingText = overflow + removeSiblings(para, false);
rearrange(remainingText);
}
if (key == 8 && para.previousElementSibling && position == 0) {
fragment = para.previousElementSibling;
remainingText = removeSiblings(fragment, true);
rearrange(remainingText);
}
}
function handlePaste(e) {
if (e.target.tagName != 'P') {
return;
}
overflow = e.target.textContent + removeSiblings(fragment, true);
rearrange(remainingText);
}
function redistributeAuto(para) {
var text = para.textContent,
fullText;
if (text.length > chunkSize) {
fullText = removeSiblings(para, true);
}
rearrange(fullText);
}
function removeSiblings(elem, includeCurrent) {
var text = '',
next;
if (includeCurrent && !elem.previousElementSibling) {
parent = elem.parentNode;
text = parent.textContent;
while (parent.hasChildNodes()) {
parent.removeChild(parent.lastChild);
}
} else {
elem = includeCurrent ? elem.previousElementSibling : elem;
while (next = elem.nextSibling) {
text += next.textContent;
elem.parentNode.removeChild(next);
}
}
return text;
}
function splitText(text, useRegex) {
var chunks = [],
i, textSize, boundary = 0;
if (useRegex) {
var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
chunks = text.match(regex) || [];
} else {
for (i = 0, textSize = text.length; i < textSize; i = boundary) {
boundary = i + chunkSize;
if (boundary <= textSize && text.charAt(boundary) == ' ') {
chunks.push(text.substring(i, boundary));
} else {
while (boundary <= textSize && text.charAt(boundary) != ' ') {
boundary++;
}
chunks.push(text.substring(i, boundary));
}
}
}
return chunks;
}
#text_land {
border: 1px solid #ccc;
padding: 25px;
margin-bottom: 30px;
}
textarea {
width: 95%;
}
label {
display: block;
width: 50%;
clear: both;
margin: 0 0 .5em;
}
label select {
width: 50%;
float: right;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: monospace;
font-size: 1em;
}
h3 {
margin: 1.2em 0;
}
div {
margin: 1.2em;
}
textarea {
width: 100%;
}
button {
padding: .5em;
}
p {
/*Here the sliles for OTHER paragraphs*/
}
#content p {
font-size: inherit;
/*So it gets the font size set on the #content div*/
padding: 1.2em .5em;
margin: 1.4em 0;
border: 1px dashed #aaa;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Import Text below, then press the button</h3>
<textarea id="textarea1" placeholder="Type text here, then press the button below." rows="5">
</textarea>
<input style="width:200px;" id="custom" placeholder="Custom Characters per box">
<br>
<button style="width:200px;" id="go">Divide Text into Paragraphs</button>
</div>
<div>
<h3 align="right">Divided Text Will Appear Below:</h3>
<hr>
<div id="content"></div>
</div>
How about this? It uses jQuery, but as you used the library in your original submission, I hope that won't be an issue:
HTML
<textarea id="input"></textarea>
<br/>
<button id='divide'>Divide</button>
<div id="paras"></div>
CSS
#input {
resize: none;
height: 200px;
width: 100%;
}
JS
$(function() {
$("#divide").click(function() {
var text = $("#input").val();
var wpp = 10 // words per paragraph
var words = text.split(" ");
var paras = [];
for (i = 0; i < words.length; i += wpp) {
paras.push(words.slice(i, i + wpp).join(" "));
}
$.each(paras, function(i, para) {
$("#paras").append("<p>" + para + "</p>");
});
});
})
JSFiddle
The following fiddle converts texts into paragraphs and the problem is the JQuery function attribute chunkSize = 100; currently defines the amount of characters for each divided paragraph to contain.
Is it possible for the user to be able to change this dynamically through the use of an <input> and <button> where the user would be able to type their desired characters for each dynamic paragraph and apply it?
Fiddle
If a new fiddle could please be provided, it would be very much appreciated, as I am still new to coding.
Thank You!
$(function() {
$('select').on('change', function() {
//Lets target the parent element, instead of P. P will inherit it's font size (css)
var targets = $('#content'),
property = this.dataset.property;
targets.css(property, this.value);
sameheight('#content p');
}).prop('selectedIndex', 0);
});
var btn = document.getElementById('go'),
textarea = document.getElementById('textarea1'),
content = document.getElementById('content'),
chunkSize = 100;
btn.addEventListener('click', initialDistribute);
content.addEventListener('keyup', handleKey);
content.addEventListener('paste', handlePaste);
function initialDistribute() {
var text = textarea.value;
while (content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
rearrange(text);
}
function rearrange(text) {
var chunks = splitText(text, false);
chunks.forEach(function(str, idx) {
para = document.createElement('P');
para.classList.add("Paragraph_CSS");
para.setAttribute('contenteditable', true);
para.textContent = str;
content.appendChild(para);
});
sameheight('#content p');
}
function handleKey(e) {
var para = e.target,
position,
key, fragment, overflow, remainingText;
key = e.which || e.keyCode || 0;
if (para.tagName != 'P') {
return;
}
if (key != 13 && key != 8) {
redistributeAuto(para);
return;
}
position = window.getSelection().getRangeAt(0).startOffset;
if (key == 13) {
fragment = para.lastChild;
overflow = fragment.textContent;
fragment.parentNode.removeChild(fragment);
remainingText = overflow + removeSiblings(para, false);
rearrange(remainingText);
}
if (key == 8 && para.previousElementSibling && position == 0) {
fragment = para.previousElementSibling;
remainingText = removeSiblings(fragment, true);
rearrange(remainingText);
}
}
function handlePaste(e) {
if (e.target.tagName != 'P') {
return;
}
overflow = e.target.textContent + removeSiblings(fragment, true);
rearrange(remainingText);
}
function redistributeAuto(para) {
var text = para.textContent,
fullText;
if (text.length > chunkSize) {
fullText = removeSiblings(para, true);
}
rearrange(fullText);
}
function removeSiblings(elem, includeCurrent) {
var text = '',
next;
if (includeCurrent && !elem.previousElementSibling) {
parent = elem.parentNode;
text = parent.textContent;
while (parent.hasChildNodes()) {
parent.removeChild(parent.lastChild);
}
} else {
elem = includeCurrent ? elem.previousElementSibling : elem;
while (next = elem.nextSibling) {
text += next.textContent;
elem.parentNode.removeChild(next);
}
}
return text;
}
function splitText(text, useRegex) {
var chunks = [],
i, textSize, boundary = 0;
if (useRegex) {
var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
chunks = text.match(regex) || [];
} else {
for (i = 0, textSize = text.length; i < textSize; i = boundary) {
boundary = i + chunkSize;
if (boundary <= textSize && text.charAt(boundary) == ' ') {
chunks.push(text.substring(i, boundary));
} else {
while (boundary <= textSize && text.charAt(boundary) != ' ') {
boundary++;
}
chunks.push(text.substring(i, boundary));
}
}
}
return chunks;
}
#text_land {
border: 1px solid #ccc;
padding: 25px;
margin-bottom: 30px;
}
textarea {
width: 95%;
}
label {
display: block;
width: 50%;
clear: both;
margin: 0 0 .5em;
}
label select {
width: 50%;
float: right;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: monospace;
font-size: 1em;
}
h3 {
margin: 1.2em 0;
}
div {
margin: 1.2em;
}
textarea {
width: 100%;
}
button {
padding: .5em;
}
p {
/*Here the sliles for OTHER paragraphs*/
}
#content p {
font-size: inherit;
/*So it gets the font size set on the #content div*/
padding: 1.2em .5em;
margin: 1.4em 0;
border: 1px dashed #aaa;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Import Text below, then press the button</h3>
<textarea id="textarea1" placeholder="Type text here, then press the button below." rows="5">
</textarea>
<input style="width:200px;" placeholder="Custom Characters per box">
<button>
Go
</button>
<br>
<button style="width:200px;" id="go">Divide Text into Paragraphs</button>
</div>
<div>
<h3 align="right">Divided Text Will Appear Below:</h3>
<hr>
<div id="content"></div>
</div>
Give an id for your input.
<input id="custom" placeholder="Custom Characters per box" style="width:200px;">
Add below code into initialDistribute function.
custom = parseInt(document.getElementById("custom").value); //Get value of the input.
chunkSize = (custom>0)?custom:100; //If Custom value is more than `0`, take that as `chunkSize` value else `100`
See Fiddle
You can use input type="number" element, button element; set chunkSize to input type="number" valueAsNumber property at click of button
html
<label>chunkSize:<input class="chunkSize" type="number" /></label>
<button class="chunkSize">
Set chunkSize
</button>
javascript
$("button.chunkSize").click(function(e) {
var _chunkSize = $("input.chunkSize")[0].valueAsNumber;
chunkSize = _chunkSize;
})
jsfiddle https://jsfiddle.net/csz0ggsw/11/
So, what I am going to do with the input tag is to insert as many as email address inside it.
<input type="text" name="email-tags"/>
To make it more user-friendly, I want to highlight each-email which is typed inside it with blue color, it looks similar like a tag in SO question which also has x button to delete the tag.
Can anybody please help me how to do this with javascript?
Thanks in advance.
This block of code actually does what you need. It's pretty advanced. I hope it suits your needs. document.getElementById("test").value contains the email addresses in an array in this example.
function setInputEmailToExtendedInput()
{
var inputs = document.querySelectorAll("input[data-type='email']");
Array.prototype.slice.call(inputs).forEach(function(element){
var node = new emailInput();
if (element.id)
{
node.container.id = element.id;
}
if (element.className)
{
node.container.className = element.className;
}
element.parentElement.replaceChild(node.container, element);
});
}
function emailInput() {
this.container = document.createElement("div");
this.container.input = document.createElement("input");
this.container.input.type = "text";
this.container.style.overflowY = "auto";
this.container.input.className = "email_input";
this.container.appendChild(this.container.input);
this.container.input.addEventListener("keydown", checkKeyUpOnEmailInputDisable(this), false);
this.evaluateTag = evaluateEmailFunction;
this.deleteTag = deleteEmailFunction;
this.container.input.addEventListener("paste", emailEvaluateOnChange(this), false);
Object.defineProperty(this, "value", {
value: [],
enumerable: false
});
Object.defineProperty(this, "placeholder", {
get: function() {
this.container.input.placeholder;
},
set: function(value) {
this.container.input.placeholder = value;
},
enumerable: false
});
}
function emailEvaluateOnChange(obj, e) {
return function(e) {
obj.evaluateTag(e.target.value);
}
}
function checkKeyUpOnEmailInputDisable(obj, e) {
return function(e) {
if (e.keyCode == 13 || e.keyCode == 32) //either enter or space
{
obj.evaluateTag(e.target.value);
return false;
} else if (e.keyCode == 8) //backspace
{
if (e.target.value.length == 0 && obj.value.length > 0) //length of the input is zero.
{
//delete tag.
obj.deleteTag();
return true;
}
} else if (e.keyCode == 27) //escape
{
//hide the input helper and blur the input.
e.target.blur();
e.preventDefault();
return false;
}
};
}
function deleteEmailFunction(tag) {
if (!tag) {
//delete the last tag
var tag = this.value.length - 1;
}
this.container.removeChild(this.container.querySelectorAll(".email_element")[tag]);
this.value.splice(tag, 1);
if (this.value.length > 0) {
var marginNode = parseInt(getComputedStyle(this.container.children[0]).getPropertyValue("margin-right"));
var width = parseInt(this.container.children[0].offsetLeft) * 2; //default padding
for (var i = 0; i < this.value.length; ++i) {
//calculate the width of all tags.
width += parseInt(this.container.children[i].offsetWidth) + marginNode;
}
this.container.input.style.width = (this.container.offsetWidth - width) - 20 + "px";
} else {
this.container.input.style.width = "100%";
}
this.container.input.focus();
}
function createEmail(value) {
var node = document.createElement("span");
node.className = "email_element";
node.innerHTML = value;
return node;
}
function evaluateEmailFunction(tagValue) {
if (tagValue.match(/[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/ig)) {
//email is valid add
var node = createEmail(tagValue.trim());
this.container.insertBefore(node, this.container.input);
this.value.push(tagValue);
var marginNode = parseInt(getComputedStyle(node).getPropertyValue("margin-right"));
var width = parseInt(this.container.children[0].offsetLeft) * 2; //default padding
for (var i = 0; i < this.value.length; ++i) {
//calculate the width of all tags.
width += parseInt(this.container.children[i].offsetWidth) + marginNode;
}
//set the width of the tag input accordingly.
this.container.input.style.width = (this.container.offsetWidth - width) - 20 + "px";
this.container.input.value = "";
this.container.input.focus();
}
}
RegExp.escape = function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
window.addEventListener("load", function(){setInputEmailToExtendedInput()}, false);
div.email_builder {
width: 500px;
height: 36px;
background-color: #ffffff;
border: 1px solid #777777;
box-sizing: border-box;
}
input.email_input {
padding: 8px 8px 8px 8px;
border: 0px solid transparent;
width: 100%;
box-sizing: border-box;
font-size: 11pt;
}
span.email_element {
display: inline-block;
padding: 6px 2px 6px 2px;
margin-right: 4px;
color: #0059B3;
font-size: 10pt;
white-space: nowrap;
cursor: pointer;
box-sizing: border-box;
}
span.email_element > span.email_remove_button {
color: #000000;
font-size: 10pt;
white-space: nowrap;
cursor: pointer;
padding-left: 12px;
font-size: 14px;
font-weight: bold;
}
span.email_element > span.email_remove_button:hover {
color: #660000;
font-size: 10pt;
white-space: nowrap;
cursor: pointer;
padding-left: 12px;
font-size: 14px;
font-weight: bold;
}
<input type="text" class="email_builder" id="test" data-type="email" />
how about this:
<from id="form" action="">
<span id="emailInput">
<input type="text" name="email-tags"/>
</span>
<span id="test"></span>
</form>
function isValidEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$(function(){
$('input').keydown(function(event){
$input = $(this);
$emailInput = $("#emailInput");
$("#test").html(event.which);
switch(event.which){
//stop for "," ";" and " "
case 188:
case 186:
case 32:
currentEmail = $.trim($input.val());
if(isValidEmail(currentEmail)){
$address = $("<span>");
$address.addClass("emailAddress");
$address.text(currentEmail);
$close=$('<span>');
$close.addClass("close").text("x");
$address.append($close);
$input.val("");
$input.before($address);
}
}
});
$("#emailInput").on("click",".close",function(){
$(this).parent().remove();
});
});
see here:
http://fiddle.jshell.net/wryjde3z/