I want this code to display information from a text input from a form on an HTML page, using the array, it would take the information into an array, then display it back on a textarea, though each time it overrides the first line, not displaying right
var count = 0;
var input = document.forms["ShoppingForm"]["choiceTxt"].value;
function listChoice(){
count++;
var arr = new Array();
arr[count] = document.forms["ShoppingForm"]["choiceTxt"].value + "\n";
for(var i = 0; i <= arr.length; i++){
document.forms["ShoppingForm"]["listDisplay"].value = count + ". " +
arr[i] + "\n";
}
}
The issue seems to be with this line var arr = new Array();. Everytime it will create a new array.
Try my declaring the array outside the function.Also the seems to be no need of the count. The value can be simply pushed in the array
var count = 0;
var arr = [];
var input = document.forms["ShoppingForm"]["choiceTxt"].value;
function listChoice(){
arr.push(document.forms["ShoppingForm"]["choiceTxt"].value + "\n");
for(var i = 0; i <= arr.length; i++){
document.forms["ShoppingForm"]["listDisplay"].value = count + ". " +
arr[i] + "\n";
}
}
Related
I have an array called countriesData that stores names for various countries, like this:
[Germany,France,Canada,Austria,Switzerland,Spain]
I'm trying to iterate over each element in that array, the idea is use each country in a query search over an external API, and then save the length of items in that external API. To put it simple, Im going through each country and counting how many items from that country are stored in an external database.
I have no problem accessing the database outside of the loop, however, I am unable to access it while inside the for iterator.This is my code:
for (var iter = 0; iter < countriesData.length; iter++) {
var obj = [];
var country = countriesData[iter]
var items;
var itemsCountry = 0;
$http.get("https://api.discogs.com/database/search?q={?country==" + country + " }&token=zwxZExVZTenjPTKumVeTDVRuniqhQLAxymdzSxUQ").then(function(response) {
items = response.data.pagination.items;
})
var str = "";
obj.push(countriesData[iter]);
obj.push(items);
for (var J = 0; J < myStats.data.length; J++) {
if (myStats.data[J].country == countriesData[iter]) {
itemsCountry++;
str += myStats.data[J].title + ", ";
}
}
obj.push(itemsCountry);
var str2 = str.substring(0, str.length - 2);
obj.push(str2);
newData.push(obj);
console.log("new obj : " + obj)
}
Basically, I need the var items to be updated acording to the length of the response data from http.get
This is an example of what I get once I console.log the obj:
France,,2,Thriller, D'eux
As you can see, the second element in the array is empty when it should have been an integer representing how many France related items where found in the database...
What is it that Im doing wrong? I get that the database is big and there might not be enough time for it to load. Any idead?
Thanks in advance :)
The problem is that your data call is asynchronous and hasn't completed before you try to push the data to the array.
function getCountryData(country) {
var obj = [];
var items;
var itemsCountry = 0;
$http.get("https://api.discogs.com/database/search?q={?country==" + country + " }&token=zwxZExVZTenjPTKumVeTDVRuniqhQLAxymdzSxUQ").then(function(response) {
items = response.data.pagination.items;
var str = "";
obj.push(country);
obj.push(items);
for (var J = 0; J < myStats.data.length; J++) {
if (myStats.data[J].country == countriesData[iter]) {
itemsCountry++;
str += myStats.data[J].title + ", ";
}
}
obj.push(itemsCountry);
var str2 = str.substring(0, str.length - 2);
obj.push(str2);
newData.push(obj);
console.log("new obj : " + obj)
})
}
for (var iter = 0; iter < countriesData.length; iter++) {
var country = countriesData[iter];
getCountryData(country);
}
I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.
I want to display duplicates found from the sheet in a Browser.Msg box and send the duplicate strings via email.
Additionally extra column could be written to that row where status "DUPLICATE - YES" would be written. However just to get it via email / in a popup would be enough.
I have tried logging the data. I have tried setting variables.
function checkDuplicates() {
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("DATA!F2:F"); // Set Any Range
// "A:A" is for Column A
// And if you want to check duplicates for whole sheet then try this:
// var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
var numRows = data.length;
var numColumns = data[0].length;
var dupes = false;
var okdupes0 = 0;
var nodupes0 = 0;
var totbookings0 = 0;
var formats = [];
var values = [];
for (var i = 0; i < numRows; i++) {
formats[i] = [];
for (var j = 0; j < numColumns; j++) {
formats[i][j] = 'WHITE';
if (data[i][j] != '') {
values.push([data[i][j], i, j]);
}
}
}
var numValues = values.length;
for (var k = 0 ; k < numValues - 1; k++) {
if (formats[values[k][1]][values[k][2]] == 'WHITE') {
for (var l = k + 1; l < numValues; l++) {
if (values[k][0] == values[l][0]) {
formats[values[k][1]][values[k][2]] = 'RED';
formats[values[l][1]][values[l][2]] = 'RED';
var dupes = true;
}
}
var okdupes = okdupes0++;
}
var totbookings = totbookings0++;
}
if (dupes) {
// var okdupes = okdupes -1;
var nodupes = totbookings - okdupes;
var emailAddress = "myemail#gmail.com"; // First column
var message = + nodupes + " Duplicate voucher(s) has been found from the system. Duplicate vouchers has been marked with red color."; // Second column
var subject = "System: " + nodupes + " Duplicate Voucher(s) Found!";
MailApp.sendEmail(emailAddress, subject, message);
Browser.msgBox('Warning!', ''+ nodupes +' Possible duplicate voucher(s) has been found and colored red! Please contact the rep who has made the sale. '+ totbookings +' bookings has been scanned through for duplicates.', Browser.Buttons.OK);
} else {
Browser.msgBox('All good!', 'No duplicate vouchers found.', Browser.Buttons.OK);
}
dataRange.setBackgroundColors(formats);
}
You could convert the array of values to a string, then use match to count occurrences.
This code works to find duplicates, even from a two dimensional array. It doesn't determine what cell the duplicate came from. The values of all the duplicates are put into an array.
function findDups() {
var testArray = [['one','two','three'],['three','four','five']];
var allDataAsString = testArray.toString();
Logger.log('allDataAsString: ' + allDataAsString);
//Create one Dimensional array of all values
var allDataInArray = allDataAsString.split(",");
var pattern;
var arrayOfDups = [];
for (var i = 0;i<allDataInArray.length;i++) {
var tempStr = allDataInArray[i];
// the g in the regular expression says to search the whole string
// rather than just find the first occurrence
var regExp = new RegExp(tempStr, "g");
var count = (allDataAsString.match(regExp) || []).length;
Logger.log('count matches: ' + count);
if (count > 1 && arrayOfDups.indexOf(tempStr) === -1) {
arrayOfDups.push(tempStr);
};
};
Logger.log('arrayOfDups: ' + arrayOfDups);
Browser.msgBox('Thest are the duplicate values: ' + arrayOfDups);
//To Do - Send Email
};
The above example code has a hard coded two dimensional array for testing purposes. There are two occurrences of an element with the value of 'three'.
This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 9 years ago.
I have data that is being returned from a JQuery .ajax function as an array.
Now the fields in that array are named & numbered i.e part1, part2, part3, etc.
I have some code below that I thought may loop through it but it returns NaN.
for (var a = 1; a <= 9; a++) {
newtext += '<div class="part">' + (exploded[0].part + a) + '</div>';
}
I couldn't get any of the sugegstions to work so I did this instead.
var h = new Array();
h[1] = exploded[0].part_1;
h[2] = exploded[0].part_2;
h[3] = exploded[0].part_3;
h[4] = exploded[0].part_4;
h[5] = exploded[0].part_5;
h[6] = exploded[0].part_6;
h[7] = exploded[0].part_7;
h[8] = exploded[0].part_8;
h[9] = exploded[0].part_9;
I know it is a bit long winded but when I am dealing with multiple songs also I can loop them all with the array keys.
Try it this way:
for (var a = 1; a <= 9; a++) {
newtext += '<div class="part">' + (exploded[0]['part_' + a]) + '</div>';
}
You can iterate/loop through the items of array like this. You should use the property 'length' of array variable which tells how many items an array have...
var myStringArray = ["part1", "part2", "part3"];
for (var i = 0; i < myStringArray.length; i++) {
alert(myStringArray[i]);
//Do something
}
What about the following:
var array=["part1", "part2", "part3"];
html=array.map(function(o){ return '<div class="part">'+o+'</div>' }).join("")
console.log(html);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Fmap
Make sure you array exploded has 10 elements becuase the index of an array start with Zero so for 9 elements you can write the code like this
for (var a = 0; a <= exploded.length; a++) {
newtext += '<div class="part">' + (exploded[a].part + a) + '</div>';
}
alert(newtext);
Modified Response to access the propery dynamically ---------
var newtext='';
alert('hi');
var exploded= {"title":"Cornerstone","firstline":"","keysignature":"C","copyright":"","part_1":"sandeep","part_2":"","part_3":"","part_4":"","part_5":"","part_6":"","part_7":"","part_8":"","part_9":"","ref":"2"};
var prop='';
var newhtml='';
for (var a = 1; a <= 9; a++) {
prop='part_' + a;
newhtml+='<div class="part">' + (exploded[prop]) + '</div>';
}
alert(newhtml);
I'm trying to code a simple piece of javascript that reads in a CSV (pasted into a textarea on a webpage) and generates SQL insert statements but I keep getting undefined values when I reference the 2D array..
Please help!
var ret = "";
//alert("called");
//split the textarea into rows of text
var lines = text.split("\n");
//the first line of text is the table name
var table = lines[0];
//the second line of text is an array of the attribute names
var attrnames = lines[1].split(",");
var values = new Array();
//create a new array for each attribute
for (var i = 0; i < attrnames.length; i++) {
//the length of each array is the total number of rows
//of text - 2 (title row and attr row)
values.push(new Array(lines.length - 2));
}
//for each subsequent row, push the values to the appropriate arrays
for (var i = 2; i < lines.length; i++) {
//get the current row (value, value, value, value)
var thisrow = lines[i].split(",");
for (var j = 0; j < attrnames.length; j++) {
//add the j-th attribute (thisrow[j]) to its array (values[j])
values[j].push(thisrow[j]);
}
}
var insertIntoTable = "";
var tableName = "";
var attrList = "";
var valueList = "";
var lead = "";
//loop through each row
for (var k = 2; k < lines.length; k++) {
// --- ONE STATEMENT ---
//create the statements
insertIntoTable = "insert into table `";
tableName = table;
attrList = "` (";
valueList = "(";
for (var i = 0; i < attrnames.length; i++){
attrList += "`" + attrnames[i] + "`,";
}
//trim the last comma, then add the closing parenthesis.
attrList = attrList.substring(0, attrList.length-1) + ") ";
lead = insertIntoTable + tableName + attrList;
for (var i = 0; i < attrnames.length; i++) {
//this always points to undefined
valueList += "'" + values[i][k-2] + "', ";
}
lead += (" values " + valueList);
lead = lead.substring(0, lead.length-2) + ");\n";
ret += lead;
}
alert(ret);
In JavaScript you do not need to set the length of arrays. They are more like ArrayLists or something; read more at MDN's documentation.
When you do
var x = new Array(10); // array with "length" set to 10
x.push("somevalue");
then the value will be inserted at x[10] - at the end of the list. Log it in the console to see it yourself.
So either you drop the push() and use absolute indizes instead, or initialize the array as empty - best with the array literal syntax: []. The relevant area of your code should then look like this:
//create a new empty array for each attribute
for(var i = 0; i<attrnames.length; i++){
values.push([]);
}
You are making an array of length n, where n is the number of rows, and then you are pushing on n more elements of data. Start with 0 length arrays and you will be fine:
//create a new array for each attribute
for(var i = 0; i<attrnames.length; i++){
values.push(new Array(0)); // or '[]' -> the length of each array **will be** the total number of rows of text-2 (title row and attr row)
}
I would add caution that pasted data will be prone to lots of errors and potential security issues, such as SQL injection attacks. Aside from that, what happens if you have extra \ns at the end of your data? You will end up with more undefined data.