There's a textarea in the webpage to enable user to add address. User may enter 'n' number of addresses by clicking on the Add Address button. When user clicks on the Display Address button, all the addresses entered should be displayed inside the "result" div tag as per following format:
Address 1
Address entered by user
Address 2
Address entered by user
.....
Here's the HTML code
<div id="body" align="left">
<h2>Address Details</h2>
Enter the Address : <textarea id="address"></textarea><br>
<button id="add" onclick="addAddress();">Add Address</button>
<button id="display" onclick="displayAddress();">Display Address</button>
</div>
<div id="result" align="right"></div>
Here's the JS function to accept the address and store it in an array:
var address = [];
function addAddress(){
var addr = document.getElementById("address");
if(addr.value.replace(/^\s+|\s+$/gm,'') !=="") {
address.push(addr.value);
addr.value = "";
}
}
And here's the function to display the address inside the result div in the specified format (which does not work)
function displayAddress(){
var display = [];
var addrno = [];
var result = document.getElementById("result");
for(var i=0; i<address.length; i++){
display[i] = address[i];
addrno[i] = "Address "+(i+1);
}
result.innerHTML = addrno[i]+"<br>"+display[i]+"<br>";
}
Any help would be greatly appreciated.
Hm, if I understand your question correctly, you could try doing something like this:
function displayAddress(){
var display = [];
var addrno = [];
var result = document.getElementById("result");
for(var i=0; i<address.length; i++){
display[i] = address[i];
addrno[i] = "Address "+(i+1);
result.innerHTML += addrno[i]+"<br>"+display[i]+"<br>";
}
}
All I changed was move result.innerHTML += addrno[i]+"<br>"+display[i]+"<br>"; inside your for loop so it can access the variable i uppon each itteration and changed it so it added the string addrno[i]+"<br>"+display[i]+"<br>"; to the DOM by using += on result.innerHTML rather than = (so it doesn't override it, rather it appends to it)
Related
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 != "";
});
}
<html>
<body>
//My text area
<textarea id="emailTextarea" rows ="30" cols="30" >
sara#yahoo.com
adam#yahoo.com
todd#yahoo.com
henry#yahoo.com
wright#yahoo.com
</textarea>
<p id="demo"></p>
<script>
//Getting input from the textarea for the email list
//The email list
var emailList = document.getElementById("emailTextarea").value;
//function to remove the yahoo extension
//remove the extension
var emailUserHash = emailList.reduce(function(emailUsers, email, i) {
var username = email.slice(0, email.indexOf('yahoo.com'));
if(!emailUsers[username]) emailUsers[username] = true;
return emailUsers;
}, {});
//calling the emailUserHash function
//call the emailUserHash function
var emailUsers = Object.keys(emailUserHash)
//Sort the email list
//sort the email list
emailUsers.sort();
//Print out the list
//output the list
document.write(emailUsers.join('</br>'));
</script>
</body>
Think this might be what you are trying to accomplish:
var emailList = document.getElementById("emailTextarea").value;
var emailListArray = emailList.split("\n");
var usernamesArray = emailListArray.map(function(val, index, arr) {
return val.slice(0, val.indexOf('#yahoo.com'));
});
var sortedUsernames = usernamesArray.sort();
document.write(sortedUsernames.join('</br>'));
This will output the list of email usernames sorted and with the #yahoo.com removed
You shall parse your textarea to array.
I made example with JQuery: https://jsfiddle.net/k8te23mf/
var arrayOfLines = $('#emailTextarea').val().split('#yahoo.com\n');
$('#demo').append(arrayOfLines+', ');
I was hoping someone can help me figure out what I'm doing wrong... There's this exercise in the Eloquent JS book that asks you to write some code that can suggest words/values to users as they type... The code I've written is below. What happens is that when I run the code, the div element's text content changes to the wrong value. Specifically, it's set to a string of all the elements inside the array 'terms'. I really cant figure out why this happens!
<input type="text" id="field">
<div id="suggestions" style="cursor: pointer"></div>
<script>
// Builds up an array with global variable names, like
// 'alert', 'document', and 'scrollTo'
var terms = [];
for (var name in window)
terms.push(name);
var input = document.querySelector('input');
var div = document.querySelector('#suggestions');
input.addEventListener("input", function(event){
var last = input.value.lastIndexOf(" ")+1;
var check = input.value.slice(last);
var reg = new RegExp(check);
for (var i=0; i<terms.length; i++) {
if (reg.test(terms[i])) {
var text = document.createTextNode(terms[i]);
div.appendChild(text)};
};
})
</script>
I guess you forgot to clean the div before each change in the input.
I also added a space after each word to make the output more readable.
// Builds up an array with global variable names, like
// 'alert', 'document', and 'scrollTo'
var terms = [];
for (var name in window)
terms.push(name);
var input = document.querySelector('input');
var div = document.querySelector('#suggestions');
input.addEventListener("input", function(event){
div.innerHTML = '';
var last = input.value.lastIndexOf(" ")+1;
var check = input.value.slice(last);
var reg = new RegExp(check);
for (var i=0; i<terms.length; i++) {
if (reg.test(terms[i])) {
var text = document.createTextNode(terms[i] + ' ');
div.appendChild(text)};
};
})
<input type="text" id="field">
<div id="suggestions" style="cursor: pointer"></div>
With this code, you will display the name of the properties from the window object that contains the last word from the input. Try it writting "window location document". Is it what you are looking for?
I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
But in this task, firstly I try to catch that input in javascript file, and I am failing in the same. Can you tell me for this, which command will I use ?
Till now my work is :-
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT FILE:-
function addString(x) {
var val = x.name.value;
//var s = document.getElementById("name_id").getElementValue;//x.name.value;
alert(val);
}
EDITED
My New JAVASCRIPT FILE IS :-
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the string, but unable to show on the web page.
See this fiddle: http://jsfiddle.net/MjyRt/
Javascript was almost right
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
alert(s);
}
Try to use jQuery (simpler)
function addString() {
var s = $('#name_id').val();//value of input;
$('#list').append(s+"<br/>");//list with entries
}
<div id='list'>
</div>
I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.