proper use of length in JS - javascript

I am attempting to print out lables (bar codes) from a table using JS (the table is using JQ Tablesorter) and the barcode jquery. My issue is that I need to iterate through all of the isbn's and it is showing one number per line. Here is the code I have:
$("#barcode").live('click', function(){
var title="";
var isbn="";
var first = "";
var second = "";
var indexGlobal = 0;
$('#acctRecords tbody tr').each(function()
{
isbn += $(this).find('#tableISBN').html();
title += $(this).find('#tableTitle').html();
}); //end of acctRecords tbody function
//Print the bar codes
var x=0;
for (x=0;x<isbn.length;x++)
{
first += '$("#'+indexGlobal+'").barcode("'+isbn[x]+'", "codabar",{barHeight:40, fontSize:30, output:"bmp"});';
second += '<div class="wrapper"><div id="'+indexGlobal+'"></div><div class="fullSKU">&nbsp &nbsp &nbsp '+isbn[x]+
'</div><br/><div class="title">'+title[x]+'</div></div><br/><br/>';
indexGlobal++;
}
var barcode = window.open('','BarcodeWindow','width=400');
var html = '<html><head><title>Barcode</title><style type="text/css">'+
'.page-break{display:block; page-break-before:always; }'+
'body{width: 8.25in;-moz-column-count:2; -webkit-column-count:2;column-count:2;}'+
'.wrapper{height: 2.5in;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
I am pretty sure that the issue is with these lines:
var x=0;
for (x=0;x<isbn.length;x++)
For example if an isbn is 9780596515898 I am getting 9 on the first line, 7 on the second, 8 on the third etc.
How do I get it to print out the entire isbn on one line?

Nope, those 2 lines are fine. But these 2, on the other hand...
var isbn="";
...
isbn += $(this).find('#tableISBN').html();
This makes isbn a string. And you are just making the string longer every time you add an isbn to it. "string".length will tell you the number of characters in that string, which is why you get one character per iteration.
You want an array instead, which you append items to with the [].push() method. [].length will tell you the number of items in that array.
var isbn = [];
...
isbn.push($(this).find('#tableISBN').html());
for (var x=0; x<isbn.length; x++) {
isbn[x]; // one isbn
}

Related

how to add last three lines of textarea to three different variables?

I have a html file with textarea tag in which i will copy and paste some text with multiple lines and i want to get the last three lines each separately in three different variables using javascript.
textarea is assigned an id="txt".
Function clicked is assigned to a button in html file.
function clicked(){
var txt = document.getElementById("txt");
var original = txt.value; //original text transfered to original variable
var lastline = //add last line in this variable
var secondlast = //add second last line in this variable
var thirdlast = //add third last line in this variable
var modified = //add text without these three lines in this variable
console.log(lastline); //how are you
console.log(secondlast); //now is the time
console.log(thirdlast); //helloo there
console.log(modified); //school data is the important
//checking home
//not there
}
text inputed in textarea:
school data is the important
checking home
not there
helloo there
now is the time
how are you
output:
how are you
now is the time
helloo there
school data is the important
checking home
not there
simple function:
function letsgo() {
var area= document.getElementById("mytext"),
//get all the lines in the textarea, seperated by \n or \r\n
lines = area.value.match(/[^\r\n]+/g),
//get bottom 3 lines, reverse them
bottom3 = lines.slice(-3).reverse();
var lastline=bottom3[0];
var secondlast=bottom3[1];
var thirdlast=bottom3[2];
//get all text except bottom 3 lines, joining them together with linefeed again
var rest = lines.slice(0, -3).join("\n");
//glue bottom3 and rest together
var result=bottom3.join("\n")+"\n"+rest;
//put in the textarea again
area.value=result;
}
Line breaks within the value of a textarea are represented by line break characters rather than an HTML <br> element,].
You can get the individual lines by normalizing the line breaks to \n and then calling the split() method on the textarea's value.
Here is a utility function that calls a function for every line of a textarea value:
function actOnEachLine(textarea, func) {
var lines = textarea.value.replace(/\r\n/g, "\n").split("\n");
var newLines, i;
// Use the map() method of Array where available
if (typeof lines.map != "undefined") {
newLines = lines.map(func);
} else {
newLines = [];
i = lines.length;
while (i--) {
newLines[i] = func(lines[i]);
}
}
textarea.value = newLines.join("\r\n");
}
var textarea = document.getElementById("txt");
var lines; // Store your lines in an array
actOnEachLine(textarea, function(line) {
lines.push(line) //
});
This works simply.
var lastline,secondlast,thirdlast,modified;
function parse()
{
var elem = document.getElementById("txt");
var text = elem.value;
var arr = text.replace(/\n/g,"$").split("$");
if(arr.length) lastline = arr.pop();
if(arr.length) secondlast = arr.pop();
if(arr.length) thirdlast = arr.pop();
modified = arr.join("\n");
console.log(lastline,secondlast,thirdlast);
console.log(modified);
}
<textarea id="txt"></textarea>
<button onclick="parse()">Parse</button>

jQuery for loop with array (Count array)

I have below function:
$(".import-shipments").on("click", function(){
var sendinger = $('#shipments').val().split("/\n/");
for(var i = 0; i < sendinger.length; i++){
console.log(sendinger[i]); //This returns 3 lines
addRow(i,"#rows") //It only adds 1 line
}
});
Which takes the values in my textarea, and count each value per line.
I then have below function, which should append a new "row", for each value:
function addRow(id, element){
var row = '<div class="row">'+
'<div>#'+id+'</div>'
'</div>';
$(element).append(row);
}
The problem is, that above only appends one row, when it should append 3.
Please see this jsFiddle for an example on how above works.
What I want to do is, for each line in the text area, it should also run the addRow() function for each line.
You are using wrong argument in split function. You are mixing regex and string here. which returns only one element in seninger array. it should be:
var sendinger = $('#shipments').val().split(/\n/); //USING Regex
or
var sendinger = $('#shipments').val().split("\n"); //USING String
Working Demo

Array.push.setAnyFormatting('red')?

Description:
Stack Overflow user mhawksey recently did some fantastic optimization of my code, and in doing so, introduced me to super efficient array pushes. But working with arrays is kind of difficult, because I can't seem to be able to use functions I can when using the traditional .getRange/.setValue approach.
Problem:
I need to integrate .setFontColors('red') and .setBackgroundColors('white').
Code and Images:
First, I will post the code. Second, an image of what the currently code does. Third, an image of what the code needs to do.
function format() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var lastRow = s.getLastRow();
var row;
//gets a [][] of all values in the column
var data = s.getRange("A:A").getValues();
//we are going to build a [][] to output result
var output = [];
//loop through all cells in column A
for (row = 0; row < lastRow; row++) {
var cellValue = data[row][0];
var dash = false;
if (typeof cellValue === 'string') {
dash = cellValue.substring(0, 1);
//if a number copy to our output array
} else {
output.push([cellValue]);
}
//if -dash
if (dash === "-") {
//build first + last name
var name = (data[(row+1)][0]+" "+data[(row+2)][0]).trim();
//add row for the -state (e.g. -MI)
output.push([cellValue]);
output.push([name]);
output.push(["Order complete"]);
//add a blank row
output.push([""]);
//jump an extra row to speed things up
row++;
}
}
//set the values we've made in our output [][] array
s.getRange(1, 1, output.length).setValues(output);
}
This is what the code does:
This is what I'm trying to achieve:
Update:
I've appended a simple, working formatting loop. The problem is, when I run it on a longer column of data, it takes too long to process. From what I understand of the comments, I cannot quickly format a spreadsheet. Am I wrong?
Appended formatting code:
//other variables
var range1;
//loop through column A
for (var row = 0; row < lastRow; row++) {
range1 = s.getRange(row + 1, 1);
//define offsets for if statement
var offset1 = range1.offset(1, 0);
var offset2 = range1.offset(2, 0);
//substring cannot run on numbers, so...
cellValue = range1.getValue();
if (typeof cellValue === 'number') {continue;};
dash = cellValue.substring(0, 1);
//if -
if (dash === "-") {
offset1.setFontColor('red');
offset2.setBackground('green');
};
};
You can use all the various spreadsheet methods to get and set colors, font sizes, font weights, etc. to and from distinct arrays but you can not mix these "attributes" in one single item. See the doc here.
Or even handier, in your script editor write a script that defines a range and play with the auto complete to see everything you can do with it...
(control+space keys)
edit following your code update.
You should create a second array that holds all the background colors of your range and fill it according to your needs.
In the code below I build the array in parrallels with your output array, not very elegantly but rather systematically to show how it works.
Note that null value means "no background color" while #0F0 is the hexadecimal code for green but you can also use the 'green' string if you prefer...
...
var output = [];
var backGrounds=[]
//loop through all cells in column A
for (row = 0; row < lastRow; row++) {
var cellValue = data[row][0];
var dash = false;
if (typeof cellValue === 'string') {
dash = cellValue.substring(0, 1);
//if a number copy to our output array
} else {
output.push([cellValue]);
backGrounds.push([null]);
}
//if -dash
if (dash === "-") {
//build first + last name
var name = (data[(row+1)][0]+" "+data[(row+2)][0]).trim();
//add row for the -state (e.g. -MI)
output.push([cellValue]);
backGrounds.push([null]);
output.push([name]);
backGrounds.push([null]);
output.push(["Order complete"]);
backGrounds.push(['#0F0']);
//add a blank row
output.push([""]);
backGrounds.push([null]);
//jump an extra row to speed things up
row++;
}
}
s.getRange(1, 1, output.length).setBackgrounds(backGrounds);
...
REMARK: The OP did a huge change from revision 1 to revision 3. Following is the content taken from the source of the revision 1.
Is it possible to push text to a spreadsheet with formatting such
as .setFontColor, .setBackgroundColor or .setBorder? I've been
monkeying around with code but never get an error message. It just
doesn't do anything. I'm working with something like this:
if (cell === "This should be red") {
var redCell = (data[(row)][0]).setFontColor('red');
array.push([redCell]);
}
Following is my answer to the revision 1.
To copy the value and format from one cell or range to another use copyTo(destination).
From the above link
// The code below will copy the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
var rangeToCopy = sheet.getRange(1, 1, sheet.getMaxRows(), 5);
rangeToCopy.copyTo(sheet.getRange(1, 6));
}

function to change argument to another sign

I dynamically create this list element and information a user has typed in shows up in it when a button is clicked 'info' is text and shuld show as it is but 'grade' is a number that i want to convert to another sign with the function changeNumber() but I am new to javascript and cant figure out how to make this function, can anyone give a suggestion or point me in the right direction?
var list = $("#filmlista");
var list_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = list_array[0][1];
var element = '<li class="lista">' + list + '<span class="grade">'+ changeNumber(grade) +'</span></li>';
list.append(element);
}
should I use innerHTML? not shure I understand how it works? and how do I use the replace method if I have to replace many different numbers to the amount of signs the number is?
for example if the number is 5 it should show up as: *****, if number is 3 show up as: *** and so on
Here's some code that should do the trick:
Add this function into your script.
function changeNumber(number) {
var finalProduct = "";
for (var i = 0; i < number; i++) {
finalProduct += "*";
}
return finalProduct;
}
Replace the updateFilmsList with this code.
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = changeNumber(list_array[0][1]);
var element = '<li class="lista">' + list + '<span class="grade">'+ grade +'</span></li>';
list.append(element);
It looks like you're trying to do something like PHP's str_repeat. In that case, take a look at str_repeat from PHPJS
There are options other than a loop:
function charString(n, c) {
n = n? ++n : 0;
return new Array(n).join(c);
}
charString(3, '*'); // ***
You can use innerHTML to set the text content of an element provided none of the text might be mistaken for markup. Otherwise, set the textContent (W3C compliant) or innerText (IE proprietary but widely implemented) property as appropriate.

Adding names to an array and outputting them to a table

I'm having some trouble getting my code to work. This is what I have so far.
function outputNamesAndTotal() {
var name;
var outputTable;
var inputForm;
var nameArray;
var outputDiv;
outputDiv = document.getElementById("outputDiv");
inputForm = document.getElementById("inputForm");
outputTable = document.getElementById("outputTable");
name = inputForm.name.value;
nameArray = [];
nameArray.push(name);
for (var i = 0; i > nameArray.length; i++) {
outputTable.innerHTML += "<tr>" + nameArray[i] + "</tr>";
}
inputForm.name.focus();
inputForm.name.select();
return false;
}
When I add the loop it breaks the code completely, but I can't figure out why.
What I'm trying to do is use an HTML form to get a name from the user. Once the user enters the name, the program adds the name to the array, and outputs each array entry to a row in a table.
It's pretty basic, but it's still giving me all kinds of trouble!
I think you are clearing your array of names every time you call the function. You should bring the line:
nameArray = [];
out and make it global.
I ran a quick test and the following code works in at least FireFox
Edited to use appendChild
<html>
<head>
<script type='text/javascript'>
var names = [];
function addName() {
var nameTxt = document.getElementById('name_txt');
var name = nameTxt.value;
names.push(name);
var outTable = document.getElementById('out_tbl');
var row = document.createElement('tr');
var entry = document.createElement('td');
var txt = document.createTextNode(name);
entry.appendChild(txt);
row.appendChild(entry);
outTable.appendChild(row);
var numDiv = document.getElementById('num_div');
removeAllChildren(numDiv);
var numTxt = document.createTextNode('You have ' + names.length + ' names');
numDiv.appendChild(numTxt);
}
function removeAllChildren(e) {
while (e.hasChildNodes()) {
e.removeChild(e.firstChild);
}
}
</script>
</head>
<body>
<table id='out_tbl'>
</table>
<div id='num_div'>You have 0 names</div>
<input id='name_txt' type='text'/>
<button onclick="addName()">CLICK</button>
</body>
</html>
Edit: Oh yeah and you are the fact that you are looping through the array every time. If you "globalize" the name array, you're gonna print the whole array every time you add a name.
Edit x2: the code you originally posted had nameArray as a local variable inside the function. This effectively clears the array every time you call the function. Then every time you call the function you add the current name to the now empty array, and loop through all 1 (one) elements that the array now holds.
What you want to do is "globalize" the name array, and remove the loop from your function. This will allow you to build up your name array across multiple calls, and works the way that you want it.
Also, innerHTML is not really the best way to add things to the page. I would suggest using appendChild().
-C
for (var i = 0; i > nameArray.length; i++) {
I think you mean i < nameArray.length

Categories

Resources