Json Pretty Print with syntactic coloration - javascript

I'm trying to pretty print my json data in html, and do some syntactic coloration.
But I'm having a little issue with empty values (empty list, empty string) in my code.
Here is the code :
if (!library)
var library = {};
function isInt(value) {
return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
};
library.json = {
replacer: function(match, pIndent, pKey, pVal, pEnd) {
var int = '<span class=json-int>';
var key = '<span class=json-key>';
var val = '<span class=json-value>';
var str = '<span class=json-string>';
var r = pIndent || '';
if (pKey)
r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
if (pVal)
//r = r + (pVal[0] == '"'i ? str : val) + pVal + '</span>';
r = r + (isInt(pVal) ? int : str) + pVal + '</span>';
return r + (pEnd || '');
},
prettyPrint: function(obj) {
var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
return JSON.stringify(obj, null, 3)
.replace(/&/g, '&').replace(/\\"/g, '"')
.replace(/</g, '<').replace(/>/g, '>')
.replace(jsonLine, library.json.replacer);
}
};
var lint = {
"LintResult": "FAILED",
"CFN_NAG": [
{
"filename": "sam.yaml",
"file_results": {
"failure_count": 0,
"violations": []
}
}
],
"Comment": "If above CFN_NAG key has None value, check code execution log for errors/exceptions"
}
$('#lint').html(library.json.prettyPrint(lint));
//document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);
pre {
background-color: ghostwhite;
bovrder: 1px solid silver;
padding: 10px 20px;
margin: 20px;
}
.json-key {
color: brown;
}
.json-value {
color: navy;
}
.json-string {
color: olive;
}
.json-int {
color: fuchsia;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="background-color:lightblue">
<h1>JSON Data:</h1>
<pre id="lint"></pre>
</div>
<p>A JSON string with 12 spaces per indentation.</p>
In the above code, the lint json variable has an empty list value for the violations item, and then this key is not print with the right color, it's just not processed.
I tried different way but I don't understand what is wrong.
You can try the code your self and will notice that the syntactic coloration doesn't work for this last item.

This might help you out:
function output(inp) {
document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
var obj = {
"LintResult": "FAILED",
"CFN_NAG": [
{
"filename": "sam.yaml",
"file_results": {
"failure_count": 0,
"violations": []
}
}
],
"Comment": "If above CFN_NAG key has None value, check code execution log for errors/exceptions"
};
var str = JSON.stringify(obj, undefined, 4);
output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; background: ghostwhite }
.string { color: olive; }
.number { color: fuchsia; }
.boolean { color: navy; }
.null { color: magenta; }
.key { color: brown; }

Related

How to put table with data array in javascript

I have my javascript with a function to add tables with loop but i want to add the format tables with my data from my json and send it to my email but when i send it, it always empty. The result should be tables with automaticly insert all data with tables there.
and the json that show up is always like this
Items [
{ org: four,
online: true,
id: 1,
endpoint: ovcx
}
]
let tableContent = ""
let stats = document.getElementById("status")
function tables() {
tableContent += `<thead><tr><th class="tc-head" colspan="5">` + data[i].org + "</th></tr></thead>"
+ `<tr><td class="tc-row">ID</td><td class="tc-row">EndPoint</td><td class="tc-row">Updated At</td><td class="tc-row">Exp</td><td class="tc-row">Status</td></tr></tbody>`
}
function tablesinfo() {
tableContent +=
`<tbody><tr><td class="tc-col">` + data[j].id + "</td>"
+ `<td class="tc-col">` + data[j].endpoint + "</td>"
// + `<td class="tc-col">` + data[j].updatedAt + "</td>"
// + `<td class="tc-col">` + data[j].exp + "</td>"
+ `<td id="status">` + data[j].online + "</td>"
}
// let data = [
// { org: "Four", id: "1", endpoint: "ovcx", online: "True" },
// { org: "Four", id: "2", endpoint: "ovcx", online: "False" },
// { org: "Four", id: "3", endpoint: "ovcx", online: "True" },
// { org: "Four", id: "4", endpoint: "ovcx", online: "False" },
// { org: "BMW", id: "1", endpoint: "ovcx", online: "True" },
// { org: "BMW", id: "2", endpoint: "ovcx", online: "True" },
// ]
for (i = 0; i < data.length; i++) {
if (i == 0) {
tables()
for (j = 0; j < data.length; j++) {
if (data[i].org == data[j].org) {
tablesinfo()
// if (data[j].online == false && data[j].online == filter[j].online) {
// stats[j].classList.add('red');
// }
// else if (filter[j] && data[j].online == false) {
// stats[j].classList.add('white')
// }
// else {
// stats[j].classList.add('green');
// }
}
else if (data[j].org != data[j].org) {
j++
}
}
}
else if (data[i].org != data[i - 1].org) {
tables()
for (j = 0; j < data.length; j++) {
if (data[i].org == data[j].org) {
tablesinfo()
// if (data[j].online == false) {
// stats[j].classList.add('red');
// }
// else if (filter[j] && data[j].online == false) {
// stats[j].classList.add('white')
// }
// else {
// stats[j].classList.add('green');
// }
}
else if (data[j].org != data[j].org) {
j++
}
}
}
}
output.innerHTML = tableContent;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Charger Station Status</title>
<style type="text/css">
.tc {
border-collapse: collapse;
border-color: #9abad9;
border-spacing: 0;
}
.tc td {
background-color: #ebf5ff;
border-color: #9abad9;
border-style: solid;
border-width: 1px;
color: #444;
font-family: Arial, sans-serif;
font-size: 14px;
overflow: hidden;
padding: 10px 5px;
word-break: normal;
}
.tc th {
background-color: #409cff;
border-color: #9abad9;
border-style: solid;
border-width: 1px;
color: #fff;
font-family: Arial, sans-serif;
font-size: 14px;
font-weight: normal;
overflow: hidden;
padding: 10px 5px;
word-break: normal;
}
.tc .tc-row {
background-color: #efefef;
border-color: inherit;
text-align: center;
vertical-align: top;
}
.tc .tc-head {
background-color: #9aff99;
border-color: inherit;
font-weight: bold;
text-align: center;
vertical-align: top;
}
.tc #status {
border-color: inherit;
text-align: left;
vertical-align: top;
}
.tc .tc-col{
border-color: inherit;
text-align: left;
vertical-align: top;
}
.red{
background-color: red;
color: blue;
}
.green{
color: #409cff;
background-color: green;
}
.green{
color: #000000;
background-color: white;
}
#media screen and (max-width: 767px) {
.tc {
width: auto !important;
}
.tc col {
width: auto !important;
}
.tc-wrap {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
}
</style>
</head>
<body>
<header>test</header>
<div class="tc-wrap">
<table class="tc" id="output">
</table>
</div>
<script src="script.js"></script>
</body>
</html>
async function listItems(){
try {
console.log('========data scan=======');
const data = await docClient.scan( params ).promise()
const filter = data.Items.filter( ( item ) => !item.online && item.exp <= Math.floor( ( new Date( Date.now() ) ).getTime() / 1000.0 ) )
console.log('filter', filter)
const scanning = fs.readFileSync(
`./table.html`,
"utf8")
if ( filter.length >= 1 ) {
const to = 'myemail#gmail.com';
const subject = 'EV Scanning Data!!!';
const text = mustache.render(scanning, { ...data, ...filter })
const send = await sendEmail( to, subject, text );
console.log( 'send', send, 'data', data );
filter.map( item => {
let putItemParams = {
TableName: tableListStation,
Item: {
id: item.id,
org: item.org,
online: item.online,
endpoint: item.endpoint,
exp: Math.floor( ( new Date( Date.now() + 172800000 ) ).getTime() / 1000.0 ),
updatedAt: momentGetDateJKT()
}
};
console.log('item params', putItemParams)
docClient.put( putItemParams, ( err, datadb ) => {
if ( err ) {
console.log('error push')
return({ message: err.message });
} else {
console.log('oke', datadb)
return data;
}
} );
})
}
return data
} catch (err) {
return err
}
}
I want it to be like this
you will find here how do you should process json data as described below :
function myFunction() {
var jsondata = '[{"org":"four","online":true,"id": 1,"endpoint": "ovcx"},' +
'{"org":"four","online":true,"id": 1,"endpoint": "ovcx"},' +
'{"org":"bmw","online":true,"id": 1,"endpoint": "ovcx"},' +
'{"org":"bmw","online":true,"id": 1,"endpoint": "ovcx"}]';
var jsonobj = JSON.parse(jsondata);
let tableContent = ""
let stats = document.getElementById("mytab")
let headers = []
// find headers
for (var i = 0; i < jsonobj.length; i++){
var obj = jsonobj[i];
var h = obj.org;
// find header into headers tab
if (!findHeader (headers, h)) {
headers.push (h);
}
}
// build tables
var gtab = "<table>";
for (var i = 0; i < headers.length; i++){
var h = headers[i];
gtab = gtab + '<tr>'
var stab = "<table>";
stab = stab + '<th>' + h + '</th>';
// manage data
for (var j = 0; j < jsonobj.length; j++){
var obj = jsonobj[j];
if (h === obj.org) {
stab = stab + '<tr>';
stab = stab + '<td>' + obj.id + ',</td>';
stab = stab + '<td>' + obj.endpoint + ',</td>';
stab = stab + '<td>' + obj.online + ',</td>';
stab = stab + '</tr>';
}
}
stab = stab + "</table>";
gtab = gtab + stab;
gtab = gtab + '</tr>'
}
gtab = gtab + "</table>";
console.log (gtab);
stats.innerHTML = gtab;
}
function findHeader (headers, h) {
for (var i = 0; i < headers.length; i++){
if (headers[i] === h) {
return true;
}
}
return false;
}
the html block to add generated data (without css)
<!DOCTYPE html>
<html>
<head>
<title>Javascript External Script</title>
<script src = "script.js" type = "text/javascript"/></script>
</head>
<body onload="myFunction()">
<div id="mytab">
</div>
</body>
</html>
Should give something like this in view (add css to have the right render)
hope this will help,

JS switch case in every second character in a string

The function is supposed to take a string and switch the case of every second character. For example:
input: 'HelloWorld' output: 'HElLowoRlD'
input: 'abcdefg' output: 'aBcDeFg'
input: 'TONYmontana' output: 'ToNymOnTaNa'
My function doesn't work, why?
function switchCase(text) {
for (let i = 0; i < text.length; i++) {
if (i % 2 !== 0) {
if (text[i] === text[i].toLowerCase()) {
text[i] = text[i].toUpperCase();
} else {
text[i] = text[i].toLowerCase();
}
}
}
return text;
}
You should store the new value in a string and return that from the function:
function secondCase(text) {
let newValue = ''; // declare a variable
for (let i = 0; i < text.length; i++) {
if(i % 2 !== 0) {
if (text[i] === text[i].toLowerCase()) {
newValue += text[i].toUpperCase(); // concatenate the modified letter
}
else {
newValue += text[i].toLowerCase(); // concatenate the modified letter
}
}
else newValue += text[i]; // concatenate the unmodified letter
}
return newValue; // return
}
console.log(secondCase('HelloWorld'));
console.log(secondCase('abcdefg'));
console.log(secondCase('TONYmontana'));
Because javascript strings are immutable, so code like text[i] = 'a' doesn't work.
You can convert string to array to do what you want, eg:
function toggleCase(c) {
return c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase();
}
function secondCase(text) {
return text.split('').map((c, i) => i % 2 !== 0 ? toggleCase(c) : c).join('');
}
In js strings are immutable. So u may handle your case like below
function setCharAt(str, index, chr) {
return str.substring(0, index) + chr + str.substring(index + 1);
}
function switchCase(text) {
for (let i = 0; i < text.length; i++) {
if (i % 2 !== 0) {
if (text[i] === text[i].toLowerCase()) {
text = setCharAt(text, i, text[i].toUpperCase());
} else {
text = setCharAt(text, i, text[i].toLowerCase());
}
}
}
return text;
}
The string should be written to a new string because strings are immutable. Alternative approach: map and join an array representation of the word:
const ucEverySecondChr = word => [...word]
.map( (c, i) =>
i && i%2 != 0 ? c.toUpperCase() : c.toLowerCase() )
.join('');
console.log(ucEverySecondChr("helloworld"));
console.log(ucEverySecondChr("abcdefg"))
console.log(ucEverySecondChr("TONYmontana"));
[after comment] Immutability and function scope
let log = (...strs) => document.querySelector(`#result`)
.insertAdjacentHTML(`beforeend`, strs.join(`\n`) + `\n`);
log(`<h3>About immutability of strings</h3>`);
let str = `lt4`;
str[2] = `X`;
str.toUpperCase();
str.concat(`You won't see me here`);
log(`<code>let str = \`lt4\`;`,
`<span class="comment">Whatever you do to me, I (str) `+
`won't budge ...</span>`,
`str[2] = \`X\`;`,
`str.toUpperCase();`,
`str.concat(\`You won't see me here\`);</code>`,
`[str] is immutable, so it is not changed. It's value is <b>${str}</b>`);
log(``,`---`, `[str] passed to the function exists ` +
`only within the called function scope. ` +
`The original value does not change, so the ` +
`<i>return value</i> of <code class="inline">changeStr(str);</code> is <b>${
changeStr(str)}</b>, but the <i>value of [str]</i> is still => <b>${
str}</b>`);
str = changeStr(str);
log(``,`---`,
`<code>str = changeStr(str);`,
`<span class="comment">Hey, I (str) suddenly feel different</span></code>`,
`Now you changed the original [str] by (re)assigning the return ` +
`value of <code class="inline">changeStr(str)</code>. So ` +
`the value of [str] is now <b>${str}</b>`);
let strObj = new String(`Hello`);
strObj += ` world`;
log(``, `---`,
`<code>let strObj = new String(\`Hello\`);`,
`<span class="comment">I (strObj) am incomplete, change me!</span>`,
`strObj += \` world\`;</code>`,
`To be complete: ` +
`if your string variable is a <i>real instance</i> of `+
`<code class="inline">String</code> ` +
`you can change it without (re)assigning, `+
`so the value of [strObj] is now <b>${strObj}</b>`);
function changeStr(str) {
if (str.length < 4) {
str += " => there we are!";
}
return str;
}
body {
font: normal 12px/15px verdana, arial;
margin: 2em;
}
#result {
font-familiy: monospace3;
white-space: pre-wrap;
max-width: 75vw;
}
code {
color: green;
font-family: 'Courier New';
background-color: #EEE;
display: block;
padding: 2px;
max-width: 70vw;
}
.comment {
color: #777;
}
.comment:before {
content: '// ';
}
code.inline {
display: inline-block;
}
<div id="result"></div>

Jquery multicomplete suggestion box control with keyboard

This code work perfectly. but the suggested text can't control using keyboard
when arrow key up and down. i want to control this suggested text using keyboard
how can i do this. please help..................
/*
*
* jQuery MultiComplete
* =====================
* Written by Tom Hallam
* http://tomhallam.github.com/jQuery-Multicomplete/
* Licenced with the Creative Commons Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) licence
* See: http://creativecommons.org/licenses/by-sa/3.0/
*
*/
(function ($) {
$.fn.multicomplete = function (options) {
// Set up the default options
var defaults = {
// Debug mode provides verbose error messages
debug: true,
// Source
source: [],
// AJAX Method (if source is a URL)
method: 'POST',
// Minimum length before a search can be triggered
minimum_length: 3,
// Delay before performing a search, ignored if source is local
search_delay: 500,
// Case sensitive search?
case_sensitive: false,
// Highlight found words?
highlight_results: true,
// Left offset for results panel
offset_left: 0,
// Top offset for results panel
offset_top: 5,
// Result template
result_template: function(row) {
// -- Please fill this in!
},
// Events -------
// On result click
result_click: null,
// On form submit
form_submit: null
},
// Extend the base object
settings = $.extend(defaults, options);
// Object to keep track of our timers
var timers = [],
// And our result groups
groups = {},
// The results themselves
results = [],
// And the query
query = '';
// Iterate over the selected elements and apply the behavior.
return this.each(function () {
multicomplete_init($(this));
});
// Bootstrapper function to attach events to the elements selected
function multicomplete_init(el) {
// Create a unique ID for this element
id = 'multicomplete-' + Math.floor(Math.random() * 1000);
$(el).data('multicomplete-id', id);
// Make a new key in our timer object
timers[id] = {};
// We need to set a timer for input to trigger based on a delay
$(el).on('keyup', function() {
// Keep a local copy of the value
query = $(this).val();
// Clear any old timers
window.clearTimeout(timers[id]);
// If there's nothing left in the input box, do nothing and hide my result panel
if(query.length == 0) {
$('.panel-multicomplete-results.' + id).hide();
return;
}
// Reset the results array
results = [];
// Make sure the query is hitting the minimum length constraint
if(query.length > settings.minimum_length) {
// Where are we sending this search?
switch(typeof(settings.source)) {
case 'string':
timers[id] = window.setTimeout(function(){
multicomplete_searchajax(function() {
multicomplete_render(el);
});
}, settings.search_delay);
break;
case 'object':
multicomplete_searchobject();
multicomplete_render(el);
break;
}
}
}).attr('autocomplete', 'off');
// Hide the DIV when someone clicks outside of the result pane.
$(document).on('mouseup', function(e) {
if($('.panel-multicomplete-results.' + id).has(e.target).length === 0) {
$('.panel-multicomplete-results.' + id).hide();
}
});
}
// Parse a result group
function multicomplete_parsegroup(group_results, group_name) {
// Loop through the group
$(group_results).each(function(index, row) {
for(var field in row) {
// No numbers (for now)
if(typeof row[field] == 'number') {
return true;
}
if(typeof row[field] == 'object') {
multicomplete_parsegroup(row);
}
else {
// If we find a result then push into our results array.
if(multicomplete_match(row[field])) {
results.push({
'field': field,
'row': row,
'group': group_name
});
return true;
}
}
}
});
}
// Does this string match the query
function multicomplete_match(field) {
if(settings.case_sensitive == true) {
return field.indexOf(query) > -1;
}
else {
return field.toLowerCase().indexOf(query.toLowerCase()) > -1;
}
}
// Search an object
function multicomplete_searchobject() {
if(settings.source.length == 0) {
if(settings.debug == true) {
alert('Source was set to an array, but the array was empty.');
}
}
// Loop through the source
for(var group_name in settings.source) {
if(settings.source[group_name].length)
groups[group_name] = multicomplete_parsegroup(settings.source[group_name], group_name);
}
}
// Search an AJAX endpoint
function multicomplete_searchajax(callback) {
// Perform the remote call.
ajax = $.ajax({
'type': settings.method,
'url': settings.source,
'dataType': 'json',
'data': {
'query': query
},
'success': function(data) {
// Loop through the source
for(var group_name in data) {
if(data[group_name].length)
groups[group_name] = multicomplete_parsegroup(data[group_name], group_name);
}
// Call the callback
callback.call(this, data);
},
'error': function(error) {
if(settings.debug == true) {
if(error.status == 412) {
alert('Your remote data source is not valid JSON! Remember to use double quotes instead of single.');
}
if(error.status == 404) {
alert('Your remote data source does not exist on this server.');
}
if(error.status == 500) {
alert('The remote server encountered an error whilst processing your source.');
}
}
}
});
}
// Render a search result
function multicomplete_render(el) {
// Where is the element
l = el.offset().left,
t = el.offset().top,
mc_html_class = 'panel-multicomplete-results ' + el.data('multicomplete-id'),
mc_class = '.panel-multicomplete-results.' + el.data('multicomplete-id');
// Is there already a results div for this element?
if($(mc_class).length == 0) {
// Build the div
$('<div class="' + mc_html_class + '"></div>').css({
'position': 'absolute',
'left': (l + settings.offset_left),
'top': (t + $(el).height() + settings.offset_top)
}).appendTo('body');
}
else {
$(mc_class).empty().show();
}
// Were there any results?
if(results.length == 0 && !$(mc_class + ' .panel-no-results').length) {
$('<div class="panel-no-results">No results found</div>').appendTo(mc_class);
}
else {
// Create a results div
$('<div class="results"></div>').appendTo(mc_class);
// Loop through the results and group them again
$(results).each(function(index, result) {
if($(mc_class + ' .results .' + result.group).length == 0) {
$('<div class="group ' + result.group + '"><div class="group-title">' + result.group + '</div><div class="group-items"></div></div>').appendTo(mc_class + ' .results');
}
// Cache the result row
r = $('<div class="result"></div>').appendTo(mc_class + ' .results .' + result.group + ' .group-items');
// Get the HTML for the result template
result_tmpl = settings.result_template.call(this, result.row, result.group, result.field);
// Apply the click action
$(result_tmpl).on('click', function() {
if(typeof settings.result_click == 'function') {
settings.result_click.call(this, result.row, result.group);
}
else {
multicomplete_defaultclick(result.row, result.group, el);
}
}).appendTo(r);
});
// Apply a clearfix to the groups
$('<div class="clearfix"></div>').appendTo(mc_class + ' .results .group');
// If we have the highlight option turned on then do that
if(settings.highlight_results == true) {
multicomplete_highlight($(mc_class + ' .results').get(0), query.toUpperCase());
}
}
}
// Default click action for a result
function multicomplete_defaultclick(result, group, el) {
// Is there even a form?
if($(el).closest('form').length == 0) {
}
else {
// Override the form submit to do some funky tings
$(el).closest('form').on('submit', function(e) {
// Check if we've already modified the form
if($(this).data('multicomplete-modified') == true) {
$(this).submit();
}
else {
// Stop the form from submitting
e.preventDefault();
// Modify the element
if(!!el.attr('name')) {
old_name = el.attr('name');
el.attr('name', el.attr('name' + '-mc-dummy'));
}
// Create a new hidden element with the ID
$('<input type="hidden" name="' + old_name + '" value="' + (!!result.id ? result.id : JSON.stringify(result)) + '" />').insertAfter(el);
// Add the checkpoint on to the form
$(this).data('multicomplete-modified', true);
// Submit the form
$(this).submit();
}
});
}
}
/*
highlight v3
Highlights arbitrary terms.
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
MIT license.
Johann Burkard
<http://johannburkard.de>
<mailto:jb#eaio.com>
*/
function multicomplete_highlight(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 += multicomplete_highlight(node.childNodes[i], pat);
}
}
return skip;
}
}
})(jQuery);
$(document).ready(function() {
$('#input-multicomplete').multicomplete({
minimum_length: 1,
result_template: function(result, group, matched_field) {
tmpl = '<div>';
if(!!result.image) {
tmpl += '<div class="image"><img src="' + result.image + '" /></div>';
}
tmpl += '<div>' + result.name + '</div>';
if(!!result.address) {
tmpl += '<div class="meta">' + result.address + '</div>';
}
// Only display this field if something was matched in it
if(!!result.cuisine && matched_field == 'cuisine') {
tmpl += '<div class="cuisine">Cuisine offered: ' + result.cuisine + '</div>';
}
tmpl += '</div>';
return tmpl;
},
result_click: function(row, group) {
alert('You chose "' + row.name + '" in ' + group);
},
source: {
"Attractions": [
{
"name": "The Tower of London",
"address": "London, EC3N 4AB",
"image": "http://www.hrp.org.uk/Images/TOL_Main.jpg"
},
{
"name": "Camden Lock Market",
"address": "1 Kentish Town Road, London, NW1 8",
"image": "http://www.london-attractions.info/images/attractions/camden-market.jpg"
},
{
"name": "Anne Frank Museum",
"address": "Prinsengracht 267, 1000 AS, Amsterdam",
"image": "http://upload.wikimedia.org/wikipedia/commons/thumb/9/9c/AnneFrankHouseAmsterdamtheNetherlands.jpg/220px-AnneFrankHouseAmsterdamtheNetherlands.jpg"
}
],
"Hotels": [
{
"name": "The Ritz",
"address": "150 Piccadilly, London, W1J 9BR",
"image": "http://www.londonhotels.net/images/photogallery/the-ritz-london/the-ritz-london.jpg"
},
{
"name": "51 Buckingham Gate",
"address": "51 Buckingham Gate, London, SW1E 6AF",
"image": "http://static.laterooms.com/hotelphotos/laterooms/193559/gallery/51-buckingham-gate-london_060620111405093617.jpg"
},
{
"name": "Hotel de l'Europe",
"address": "2–14 Nieuwe Doelenstraat, Amsterdam, 1012 CP ",
"image": "http://www.concierge.com/images/cnt/lists/goldlist06/europe/netherlands/amsterdam/hotel_de_leurope/amsterdam_hotel_002p.jpg"
}
],
"Restaurant": [
{
"name": "Petrus",
"address": "1 Kinnerton Street, Knightsbridge, London, SW1X 8EA",
"image": "http://berkshirereview.net/images/petrus_london_dining.jpg"
},
{
"name": "Vermeer",
"address": "Prins Hendrikkade 59-72, 1012 AD Amsterdam ",
"image": "http://www.restaurantvermeer.nl/Portals/7/UltraPhotoGallery/3425/45/[7].Vermeer---desert-2.jpg"
}
]
}
});
});
/* DEMO STYLES */
.result .image {
float: left;
margin-right: 10px;
}
.result .image img {
width: 32px;
height: 32px;
border: 1px solid #ccc;
padding: 1px;
}
.result .meta {
font-size: 11px;
color: #666;
}
.result a {
text-decoration: underline;
}
.result:hover {
background-color: #f7f7f7;
}
/*
*
* jQuery MultiComplete
* =====================
* Written by Tom Hallam
* http://tomhallam.github.com/jQuery-Multicomplete/
* Licenced with the Creative Commons Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) licence
* See: http://creativecommons.org/licenses/by-sa/3.0/
*
*/
.panel-multicomplete-results {
border: 1px solid #ccc;
width: 420px;
font-family: Tahoma;
font-size: 12px;
background: url(mc-bg.png) repeat-y;
}
.panel-multicomplete-results .result {
padding: 5px;
border-bottom: 1px solid #e7e7e7;
cursor: pointer;
}
.panel-multicomplete-results .result:last-child {
border: none;
}
.panel-multicomplete-results .group {
border-bottom: 1px solid #ccc;
}
.panel-multicomplete-results .group:last-child {
border: none;
}
.panel-multicomplete-results .group-title {
float: left;
width: 100px;
padding: 5px;
font-weight: bold;
}
.panel-multicomplete-results .group-items {
float: left;
width: 300px;
}
.highlight {
font-weight: bold;
}
/* UTILITIES */
.clearfix {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Start typing a city: <input type="text" name="multiselect" id="input-multicomplete" />
</div>
https://jsfiddle.net/ynyqed1m/

javascript:window.print() not showing barcode for printing

I am making Mean Stack App in which I need to print barcode, I am using an angular js directive for generating code 128 barcode, and it is generating well, but when I click print button (javascript:window.print()) it is not showing the barcode in printing window neither in PDF,
Here is my directive,
.directive('barcodeGenerator', [function() {
var Barcode = (function () {
var barcode = {
settings: {
barWidth: 1,
barHeight: 50,
moduleSize: 5,
showHRI: false,
addQuietZone: true,
marginHRI: 5,
bgColor: "#FFFFFF",
color: "#000000",
fontSize: 10,
posX: 0,
posY: 0
},
intval: function(val) {
var type = typeof(val);
if ( type == 'string' ) {
val = val.replace(/[^0-9-.]/g, "");
val = parseInt(val * 1, 10);
return isNaN(val) || !isFinite(val)? 0: val;
}
return type == 'number' && isFinite(val)? Math.floor(val): 0;
},
code128: {
encoding:[
"11011001100", "11001101100", "11001100110", "10010011000",
"10010001100", "10001001100", "10011001000", "10011000100",
"10001100100", "11001001000", "11001000100", "11000100100",
"10110011100", "10011011100", "10011001110", "10111001100",
"10011101100", "10011100110", "11001110010", "11001011100",
"11001001110", "11011100100", "11001110100", "11101101110",
"11101001100", "11100101100", "11100100110", "11101100100",
"11100110100", "11100110010", "11011011000", "11011000110",
"11000110110", "10100011000", "10001011000", "10001000110",
"10110001000", "10001101000", "10001100010", "11010001000",
"11000101000", "11000100010", "10110111000", "10110001110",
"10001101110", "10111011000", "10111000110", "10001110110",
"11101110110", "11010001110", "11000101110", "11011101000",
"11011100010", "11011101110", "11101011000", "11101000110",
"11100010110", "11101101000", "11101100010", "11100011010",
"11101111010", "11001000010", "11110001010", "10100110000",
"10100001100", "10010110000", "10010000110", "10000101100",
"10000100110", "10110010000", "10110000100", "10011010000",
"10011000010", "10000110100", "10000110010", "11000010010",
"11001010000", "11110111010", "11000010100", "10001111010",
"10100111100", "10010111100", "10010011110", "10111100100",
"10011110100", "10011110010", "11110100100", "11110010100",
"11110010010", "11011011110", "11011110110", "11110110110",
"10101111000", "10100011110", "10001011110", "10111101000",
"10111100010", "11110101000", "11110100010", "10111011110",
"10111101110", "11101011110", "11110101110", "11010000100",
"11010010000", "11010011100", "11000111010"
],
getDigit: function(code) {
var tableB = " !\"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
var result = "";
var sum = 0;
var isum = 0;
var i = 0;
var j = 0;
var value = 0;
// check each characters
for(i=0; i<code.length; i++){
if (tableB.indexOf(code.charAt(i)) == -1){
return("");
}
}
// check firsts characters : start with C table only if enought numeric
var tableCActivated = code.length > 1;
var c = '';
for (i=0; i<3 && i<code.length; i++) {
c = code.charAt(i);
tableCActivated &= c >= '0' && c <= '9';
}
sum = tableCActivated ? 105 : 104;
// start : [105] : C table or [104] : B table
result = this.encoding[ sum ];
i = 0;
while ( i < code.length ) {
if ( !tableCActivated) {
j = 0;
// check next character to activate C table if interresting
while ( (i + j < code.length) && (code.charAt(i+j) >= '0') && (code.charAt(i+j) <= '9') ) {
j++;
}
// 6 min everywhere or 4 mini at the end
tableCActivated = (j > 5) || ((i + j - 1 == code.length) && (j > 3));
if ( tableCActivated ){
result += this.encoding[ 99 ]; // C table
sum += ++isum * 99;
} // 2 min for table C so need table B
} else if ( (i == code.length) || (code.charAt(i) < '0') || (code.charAt(i) > '9') || (code.charAt(i+1) < '0') || (code.charAt(i+1) > '9') ) {
tableCActivated = false;
result += this.encoding[ 100 ]; // B table
sum += ++isum * 100;
}
if ( tableCActivated ) {
value = barcode.intval(code.charAt(i) + code.charAt(i+1)); // Add two characters (numeric)
i += 2;
} else {
value = tableB.indexOf( code.charAt(i) ); // Add one character
i += 1;
}
result += this.encoding[ value ];
sum += ++isum * value;
}
result += this.encoding[sum % 103];// Add CRC
result += this.encoding[106];// Stop
result += "11";// Termination bar
return(result);
}
},
bitStringTo2DArray: function( digit) {//convert a bit string to an array of array of bit char
var d = [];
d[0] = [];
for ( var i=0; i<digit.length; i++) {
d[0][i] = digit.charAt(i);
}
return(d);
},
digitToCssRenderer: function( $container, settings, digit, hri, mw, mh, type) {// css barcode renderer
var lines = digit.length;
var columns = digit[0].length;
var content = "";
var len, current;
var bar0 = "<div class='w w%s' ></div>";
var bar1 = "<div class='b b%s' ></div>";
for ( var y=0, x; y<lines; y++) {
len = 0;
current = digit[y][0];
for ( x=0; x<columns; x++){
if ( current == digit[y][x] ) {
len++;
} else {
content += (current == '0'? bar0: bar1).replace("%s", len * mw);
current = digit[y][x];
len=1;
}
}
if ( len > 0) {
content += (current == '0'? bar0: bar1).replace("%s", len * mw);
}
}
if ( settings.showHRI) {
content += "<div style=\"clear:both; width: 100%; background-color: " + settings.bgColor + "; color: " + settings.color + "; text-align: center; font-size: " + settings.fontSize + "px; margin-top: " + settings.marginHRI + "px;\">"+hri+"</div>";
}
var div = document.createElement('DIV');
div.innerHTML = content;
div.className = 'barcode '+ type +' clearfix-child';
return div;
},
digitToCss: function($container, settings, digit, hri, type) {// css 1D barcode renderer
var w = barcode.intval(settings.barWidth);
var h = barcode.intval(settings.barHeight);
return this.digitToCssRenderer($container, settings, this.bitStringTo2DArray(digit), hri, w, h, type);
}
};
var generate = function(datas, type, settings) {
var
digit = "",
hri = "",
code = "",
crc = true,
rect = false,
b2d = false
;
if ( typeof(datas) == "string") {
code = datas;
} else if (typeof(datas) == "object") {
code = typeof(datas.code) == "string" ? datas.code : "";
crc = typeof(datas.crc) != "undefined" ? datas.crc : true;
rect = typeof(datas.rect) != "undefined" ? datas.rect : false;
}
if (code == "") {
return(false);
}
if (typeof(settings) == "undefined") {
settings = [];
}
for( var name in barcode.settings) {
if ( settings[name] == undefined) {
settings[name] = barcode.settings[name];
}
}
switch (type) {
case "std25":
case "int25": {
digit = barcode.i25.getDigit(code, crc, type);
hri = barcode.i25.compute(code, crc, type);
break;
}
case "ean8":
case "ean13": {
digit = barcode.ean.getDigit(code, type);
hri = barcode.ean.compute(code, type);
break;
}
case "upc": {
digit = barcode.upc.getDigit(code);
hri = barcode.upc.compute(code);
break;
}
case "code11": {
digit = barcode.code11.getDigit(code);
hri = code;
break;
}
case "code39": {
digit = barcode.code39.getDigit(code);
hri = code;
break;
}
case "code93": {
digit = barcode.code93.getDigit(code, crc);
hri = code;
break;
}
case "code128": {
digit = barcode.code128.getDigit(code);
hri = code;
break;
}
case "codabar": {
digit = barcode.codabar.getDigit(code);
hri = code;
break;
}
case "msi": {
digit = barcode.msi.getDigit(code, crc);
hri = barcode.msi.compute(code, crc);
break;
}
case "datamatrix": {
digit = barcode.datamatrix.getDigit(code, rect);
hri = code;
b2d = true;
break;
}
}
if ( digit.length == 0) {
return this;
}
if ( !b2d && settings.addQuietZone) {
digit = "0000000000" + digit + "0000000000";
}
var fname = 'digitToCss' + (b2d ? '2D' : '');
return barcode[fname](this, settings, digit, hri, type);
};
return generate;
}());
return {
link: function(scope, element, attrs) {
attrs.$observe('barcodeGenerator', function(value){
var code = Barcode(value, "code128",{barWidth:2}),
code_wrapper = angular.element("<div class='barcode code128'></div>")
code_wrapper.append(code);
angular.element(element).html('').append(code_wrapper);
});
}
}
And here is barcode generating code,
<div ng-model='myInput' barcode-generator="{{myInput}}" style="height:208px;">
</div>
Here are the screenshots
It shows barcode on the page
But not shows up while printing
It's because some browsers has turned off rendering background-color in print mode by default. You won't force all users to mess up with browser settings, but you can replace background-color with border-width like this:
<style type="text/css" media="print">
.barcode.code128 > div.b {
border-style: solid !important;
border-color: #000000 !important;
}
.barcode.code128 .b1 {
width: 0px !important;
border-width: 0px 0px 0px 1px !important;
}
.barcode.code128 .b2 {
width: 0px !important;
border-width: 0px 0px 0px 2px !important;
}
.barcode.code128 .b3 {
width: 0px !important;
border-width: 0px 0px 0px 3px !important;
}
.barcode.code128 .b4 {
width: 0px !important;
border-width: 0px 0px 0px 4px !important;
}
.barcode.code128 .b5 {
width: 0px !important;
border-width: 0px 0px 0px 5px !important;
}
.barcode.code128 .b6 {
width: 0px !important;
border-width: 0px 0px 0px 6px !important;
}
.barcode.code128 .b7 {
width: 0px !important;
border-width: 0px 0px 0px 7px !important;
}
.barcode.code128 .b8 {
width: 0px !important;
border-width: 0px 0px 0px 8px !important;
}
.barcode.code128 .b9 {
width: 0px !important;
border-width: 0px 0px 0px 9px !important;
}
.barcode.code128 .b10 {
width: 0px !important;
border-width: 0px 0px 0px 10px !important;
}

highlighting each email in input tag

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/

Categories