LImit Characters in Java Script Print output - javascript

I am trying to limit the number of characters printed on a lable with a js file. The part of the code i am having problems with is called by a button and prints the contents from a preview box. Everything is working except the length of the title i am trying to print. When ever i add the code to limit the numbers of characters i get:
TypeError: title.substring is not a function
title = title.substring(0, 11); any ideas
// To allow for the TEMP SLU's to be printed from the main page in alpha order
$("#barcodesku").live('click', function(){
var title=[];
var sku=[];
var first = "";
var second = "";
var indexGlobal = 0;
$('#acctRecords tbody tr').each(function()
{
sku.push($(this).find('#tableSKU').html());
title.push ($(this).find('#tableTitle').html());
}); //end of acctRecords tbody function
//Print the bar codes
title = title.substring(0,16);
var x=0;
for (x=0;x<sku.length;x++){
first += '$("#'+indexGlobal+'").barcode("'+sku[x]+'", "codabar",{barHeight:40, fontSize:30, output:"bmp"});';
second += '<div class="wrapper"><img src="../images/temp.jpg" /><div id="'+indexGlobal+
'"></div><div class="fullSKU">&nbsp &nbsp &nbsp '+sku[x]+'</div><br/><div class="title", {title.substring(0,16)}; >'+title[x]+' </div></div><br/><br/>';
indexGlobal++;
}
var barcode = window.open('','BarcodeWindow','width=200');
var html = '<html><head><title>Barcode</title><style type="text/css">'+
'.page-break{display:block; page-break-before:always; }'+
'body{width: 2in;}'+
'.wrapper{height: 1in;margin-left:10px;margin-top:5px;margin-right:5px;}'+
'.fullSKU{float: left;}'+
'.shortSKU{float: right;font-size:25px;font-weight:bold;}'+
'.title{float: left;}'+
'</style><script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js"></script><script type="text/javascript" src="../barcode/jquery-barcode.js"></script><script>$(document).ready(function() {'+first+'window.print();window.close();});</script></head><body>'+second+'</body></html>';
barcode.document.open();
barcode.document.write(html);
barcode.document.close();
}); // end of click function

From your code I see title is an array of titles. You need to do the following:
for (var i = 0; i < title.length; i++) {
title[i] = title[i].substring(0, 11);
}

Related

Losing CSS styling upon printing

I am using a style sheet to properly print out a webpage. The webpage has fields sat next to each other but upon printing these fields no longer sit next to each other but instead cascade down the sheet. I have created a style sheet but I'm not sure exactly how that is supposed to stop this from happening unless I hard code into the style sheet what I want to happen. Unfortunately I can't do that because I need to print out several different pages that have different layouts.
Is there any way to fix this?
function removeLinks(printDiv) {
var all_links = document.getElementById(printDiv).getElementsByTagName("a");
for (var i = 0; i < all_links.length; i++) {
all_links[i].removeAttribute("href");
}
}
function printdiv(printDiv) {
var divCaseNote = document.getElementById(printDiv);
var oldstr = document.body.innerHTML;
var oldTitle = document.title;
if (divCaseNote != null) {
divCaseNote.style = "padding: 20px;";
innerHTML = divCaseNote.innerHTML;
}
removeLinks(printDiv);
var headstr = "<html><head rel=\"stylesheet\" media=\"all\" link href=\"/CSS/style.css\"/><title> </title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printDiv).innerHTML;
document.body.innerHTML = headstr + newstr + footstr;
document.title = oldTitle.replace(" - View Case Note", "");
window.print()
document.body.innerHTML = oldstr;
document.title = oldTitle;
EDIT: A snippet of the html output of this function. It holds all the correct divs for the columns but instead of printing the columns side by side they print cascading down the page.
<div class=\"view-value\" style=\"border-left: none;\">
Jerry</div></div></div>
<div class=\"col-md-3\"><div class=\"media-body\">
<div class=\"view-label\">Participant's Last Name</div>
<div class=\"view-value\" style=\"border-left: none;\">Field</div>
What it should look like
[
What it actually looks like after printing
The problem is that the inline styles are getting obliterated by this statement:
divCaseNote.style = "padding: 20px;";
which removes all the style attribute and replaces it with just the padding.
To add/alter the padding but nothing else you want to change just that property so try:
divCaseNote.style.padding = "20px";

Remove all HTML <button> elements with regex

I'm trying to build a program to run a function every time I press a button, and output the returned value. To do this, I use the following HTML:
<h2>Test Results:</h2>
<strong><span id='runs'>0</span> tests</strong><br>
<div id='testResults'>
<button id='test' onClick='this.parentNode.innerHTML = initiatePlanB()'>Begin</button>
</div>
Here's the javascript:
var tests = document.getElementById('runs');
var inner = document.getElementById('testResults').innerHTML;
//Here's the part I can't figure out
var wo = inner.replace(??????, '');
var out = wo + '<br><strong>Test #' + String(Number(tests.innerText) + 1) + '</strong><br>';
tests.innerText = Number(tests.innerText) + 1;
//More stuff here
return out;
Basically, I need either a regex expression, or some other function that can remove any html tag and it's contents.
Why not just find all buttons using getElementsByTagName('button')
and then remove them all?
var testCount = 0;
var tests = document.getElementById('runs');
var inner = document.getElementById('testResults')
function initiatePlanB() {
var buttons = inner.getElementsByTagName('button');
if (buttons) {
for (var i = 0; i < buttons.length; i++) {
buttons[i].remove();
}
}
testCount++;
inner.insertAdjacentHTML('beforeend', '<br><strong>Test #' + testCount + '</strong><br>');
tests.innerText = testCount;
//More stuff here
}
<h2>Test Results:</h2>
<strong><span id='runs'>0</span> tests</strong><br>
<div id='testResults'>
<button id='test' onClick='initiatePlanB()'>Begin</button>
</div>
Though you should probably just hide the buttons, or disable them.

Add getElementById with several IDs in the For loop

It is possible to add getElementById with several IDs in the For loop?
But first you have the querySelectorAll to list the IDs that have appeared.
Function that will return the formatted information if it exists:
function show_info(real_info, otp_inf) {
if(real_info.indexOf('already exists') > -1) {
var sinf = real_info.split("File '"+dir_files).pop();
var sinf = sinf.split(' Overwrite').shift();
$('#otp_'+otp_inf).html('<br><i><b class="rev-dev" style="font-size:14px">Not Encoded</b><br /><b>File \''+ sinf +'</b></i>');
}
}
Here is the problem the For loop does not work if I put the getElementById inside:
var allids = document.querySelectorAll("#all_log div"); // To list all the IDs that have appeared
for (var i = 0; i < allids.length; i++) {
if(allids[i].id.indexOf('bd_') > -1) { // Filter all IDs that start with...
var idinfo = allids[i].id.split('bd_').pop(); // Show only the unknown name of the ID that will show the final text ......
var id_info = document.getElementById(allids[i].id); // this line is not working
show_info(id_info, idinfo);
}
}
This will be the IDs:
<div id="all_log">
<?php
echo '<div class="hide_log" id="bd_'.md5(current($files)).'">'; //ID with the original text
execOutput($cmd);
echo '</div>';
echo '<div id="otp_'.md5(current($files)).'"></div>'; //ID with part of text
?>
</div>
On the line, the goal is to collect the text in html of the ID, so it went wrong:
var id_info = document.getElementById(allids[i].id); // wrong
var id_info = $('#'+allids[i].id).html(); //correct

Get second, third and so on values

I have this problem here
The problem has been solved, but my question is how can I get the second value from that, or the third one. The sheet will have many tables and at some point I will need a total for each table. Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense.
Thank you!
Kind regards,
L.E. Test file
If I understood your question correctly, instead of breaking the loop when a match to "Total" is found do whatever is needed to be done within the loop like so...
var today = toDateFormat(new Date());
var todaysColumn =
values[5].map(toDateFormat).map(Number).indexOf(+today);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1",
"dd/MM/yyyy");
for (var i=0; i<values.length; i++){
if (values[i][0]=='Total'){
nr = i;
Logger.log(nr);
var output = values[nr][todaysColumn];
// Do something with the output here I"m assuming you email it
}
}
The loop will keep going and find every "Total" and do the same thing. This answer assumes that the "Totals" are in the same column. You can get fancier with this if you only want certain tables to send and not others, but this should get you started.
I didn't quite understand the second part of your question...
"Also, is there any solution to automatically find the the array
number which contain date row for each table (instead defining this
manually). Hope my explanation make sense."
I'm guessing you want all the rows that contain "Total" in the specific column. You could instantiate a variable as an empty array like so, var totals = [];. Then instead of sending the email or whatever in the first loop you would push the row values to the array like so, totals.push(nr+1) . //adding 1 gives you the actual row number (rows count from 1 but arrays count from 0). You could then simply loop through the totals array and do whatever you wanted to do. Alternatively you could create an array of all the values instead of row numbers like totals.push(values[nr][todaysColumn]) and loop through that array. Lots of ways to solve this problem!
Ok based on our conversation below I've edited the "test" sheet and updated the code. Below are my edits
All edits have been made in your test sheet and verified working in Logger. Let me know if you have any questions.
Spreadsheet:
Added "Validation" Tab
Edited "Table" tab so the row with "Email Address" in Column A lines up with the desired lookup values (dates or categories)...this was only for the first two tables as all the others already had this criteria.
Code:
Create table/category selector...
In the editor go to File >> New >> HTMLfile
Name the file "inputHTML"
Copy and paste the following code into that file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form class="notice_form" autocomplete="off" onsubmit="formSubmit(this)" target="hidden_iframe">
<select id="tables" onchange="hideunhideCatagory(this.value)" required></select>
<p></p>
<select id="categories" style="display:none"></select>
<hr/>
<button class="submit" type="submit">Get Total</button>
</form>
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// The code in this function runs when the page is loaded.
$(function() {
var tableRunner = google.script.run.withSuccessHandler(buildTableList);
var catagoryRunner = google.script.run.withSuccessHandler(buildCatagoryList);
tableRunner.getTables();
catagoryRunner.getCategories();
});
function buildTableList(tables) {
var list = $('#tables');
list.empty();
list.append('<option></option>');
for (var i = 0; i < tables.length; i++) {
if(tables[i]==''){break;}
list.append('<option>' + tables[i] + '</option>');
}
}
function buildCatagoryList(categories) {
var list = $('#categories');
list.empty();
list.append('<option></option>');
for (var i = 0; i < categories.length; i++) {
if(categories[i]==''){break;}
list.append('<option>' + categories[i] + '</option>');
}
}
function hideunhideCatagory(tableValue){
var catElem = document.getElementById("categories");
if(tableValue == "Total Calls By Date" || tableValue == "Total Appointments by Date"){
catElem.style.display = "none"
document.required = false;
}else{
catElem.style.display = "block"
document.required = true;
}
}
function formSubmit(argTheFormElement) {
var table = $("select[id=tables]").val(),
catagory = $("select[id=categories]").val();
console.log(table)
google.script.run
.withSuccessHandler(google.script.host.close)
.getTotal(table,catagory);
}
</script>
</body>
<div id="hiframe" style="display:block; visibility:hidden; float:right">
<iframe name="hidden_iframe" height="0px" width="0px" ></iframe>
</div>
</html>
Edits to Code.gs file
Replace code in Code.gs with this...
//This is a simple trigger that creates the menu item in your sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Run Scripts Manually')
.addItem('Get Total','fncOpenMyDialog')
.addToUi();
}
//This function launches the dialog and is launched by the menu item
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('inputHTML')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Select table to get total for');
};
//main function called by clicking "Get Total" on the dialogue...variables are passed to this function from the formSubmit in the inputHTML javascript
function getTotal(table,catagory) {
function toDateFormat(date) {
try {return date.setHours(0,0,0,0);}
catch(e) {return;}
}
//get all values
var values = SpreadsheetApp
.openById("10pB0jDPG8HYolECQ3eg1lrOFjXQ6JRFwQ-llvdE2yuM")
.getSheetByName("Tables")
.getDataRange()
.getValues();
//declare/instantiate your variables
var tableHeaderRow, totalRow, tableFound = false;
//begin loop through column A in Tables Sheet
for (var i = 0; i<values.length; i++){
//test to see if values have already been found if so break the loop
if(tableFound == true){break;}
//check to see if value matches selected table
if (values[i][0]==table){
//start another loop immediately after the match row
for(var x=i+1; x<values.length; x++){
if(values[x][0] == "Email Address"){ //This header needs to consistantly denote the row that contains the headers
tableHeaderRow = x;
tableFound = true;
}else if(values[x][0] == "Total"){
totalRow = x;
break;
}
}
}
}
Logger.log("Header Row = "+tableHeaderRow)
Logger.log("Total Row = "+ totalRow)
var today = toDateFormat(new Date())
var columnToTotal;
if(catagory==''){
columnToTotal = values[tableHeaderRow].map(toDateFormat).map(Number).indexOf(+today);
}else{
columnToTotal = values[tableHeaderRow].indexOf(catagory);
}
var output = values[totalRow][columnToTotal];
Logger.log(output);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy");
//here is where you would put your code to do something with the output
}
/** The functions below are used by the form to populate the selects **/
function getTables(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var tabelCol = (cSheetHeader.indexOf("Tables")+1);
var tables = cSheet.getRange(2,tabelCol,cSheet.getLastRow(),1).getValues();
return tables.filter(function (elem){
return elem != "";
});
}
function getCatagories(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var catagoriesCol = (cSheetHeader.indexOf("Catagory")+1);
var catagories = cSheet.getRange(2,catagoriesCol,cSheet.getLastRow(),1).getValues();
return catagories.filter(function (elem){
return elem != "";
});
}

Loop through an array and concatenate the HTML for the image elements with its src's

I am trying to output pictures of words based on the users input , i was wondering if there was a way to do it through Loop through an array and concatenate the HTML for the image elements with src's set to the corresponding image?
//myArray
var Signs = new Array("signa.jpg", "signb.jpg", "signc.jpg", "signd.jpg", "signe.jpg", "signf.jpg", "signg.jpg", "signh.jpg", "signi.jpg", "signj.jpg", "signk.jpg", "signl.jpg", "signm.jpg", "signn.jpg", "signo.jpg", "signp.jpg", "signq.jpg", "signr.jpg", "signs.jpg", "signt.jpg", "signu.jpg", "signv.jpg", "signw.jpg", "signx.jpg", "signy.jpg", "signz.jpg");
$(document).ready(function () {
$("#btnGet").click(function () {
var pattern = new RegExp(/^[a-zA-Z]+$/);
var UserInput;
UserInput = $('#txt_name').val();
//splits input
UserInput = UserInput.split("");
//gets data from input
var userFirstName = trim($("#txt_name").val());
text = text.toLowerCase(); //put all text into lower case
});//end of txt_name
});//end of btnGet
//Trim function from http://www.somacon.com/p355.php
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g, "");
}
</script>
You can use code such as the following - this generates the html img tag for each letter and then injects these into a DOM element (assuming, for example, you have a div with id of "output":
var imageTags = $('#txt_name').val().split('').map (function(c) {return '<img src="img' + c + '.png" />';}, '');
$("#output").html(imageTags.join(''));
Here is a sample jsFiddle:
http://jsfiddle.net/zdmmx49k/4/

Categories

Resources