I am working on a check-in app though Google Sheets and want to make a search function that that takes a sport name as input in an HTML form and then returns information about the sport from the sheet in a HTML table. However, when I try to test the web app, nothing happens. How can I fix this?
Here is my code:
Index.html
<!DOCTYPE html>
<html>
<head>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</head>
<body>
<fieldset id="tasks-panel">
<legend>Sports</legend>
<form name="sport-form" id="sport-form">
<label for="sport-name">Search a sport by name:</label>
<input type="text" name="sport-name" id="sport-name" />
<button onclick='addTable()' id='submit-button'>Press this</button>
</form>
<p>List of things:</p>
<div id="toggle" style="display:none"></div>
</fieldset>
<?!= HtmlService.createHtmlOutputFromFile('Javascript').getContent(); ?>
</body>
</html>
Javascript.html
<script>
function addTable() {
var sportInput = $('sport-name').value();
var columnNames = ["Names", "Times"];
var dataArray = google.script.run.getSportData(sportInput);
var myTable = document.createElement('table');
$('#divResults').append(myTable);
var y = document.createElement('tr');
myTable.appendChild(y);
for(var i = 0; i < columnNames.length; i++) {
var th = document.createElement('th'),
columns = document.createTextNode(columnNames[i]);
th.appendChild(columns);
y.appendChild(th);
}
for(var i = 0 ; i < dataArray.length ; i++) {
var row= dataArray[i];
var y2 = document.createElement('tr');
for(var j = 0 ; j < row.length ; j++) {
myTable.appendChild(y2);
var th2 = document.createElement('td');
var date2 = document.createTextNode(row[j]);
th2.appendChild(date2);
y2.appendChild(th2);
}
}
}
</script>
Code.gs
//Setting up global variables
var ss = SpreadsheetApp.openById("-spreadsheetID-");
var sheet = ss.getSheetByName("Sheet1");
var sportsFromSheet = sheet.getRange("D4:D12");
var namesFromSheet = sheet.getRange("B4:B12").getValues();
var timesFromSheet = sheet.getRange("A4:A12").getValues();
var NAMES = [];
var TIMES = [];
var OUTPUT = [];
//doGet function
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate()
.setTitle('Check In Data')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
//Gets both names and times of checked-in people
function getSportData(input) {
var sportInput = input;
getNamesInSport(sportInput);
getTimesInSport(sportInput);
OUTPUT = [
[NAMES],
[TIMES]
];
Logger.log(OUTPUT);
return OUTPUT;
}
//Puts the names of every person from an inputted sport into an array.
function getNamesInSport(input) {
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i++) {
if(data[i] == input){
NAMES.push(namesFromSheet[i][0]);
}
}
}
//Puts the times of every person from an inputted sport into an array.
function getTimesInSport(input){
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i ++) {
if(data[i] == input){
TIMES.push(timesFromSheet[i][0]);
}
}
}
JQuery id selectors must be prefixed with # so to grab the value from the the 'sport-name' input you'll need to select it using
var sportInput = $('#sport-name').val();
Additionally, as Robin comments above, if you want to use the JQuery library you'll need to load it, the code you've shown indicates you might not have done this?
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
Although if this were the case you'd probably be seeing a '$ is not defined' error straight away.
Related
I wrote a GAS code to check if the employee is In or Not in (extracting data from Google sheets).
The console log give me the right answer but When I click on the button the answer doesn't appear at the front end. Can you help me to troubleshoot on where I went wrong?
<div>
<script>
function onStatus(notify) {
var employee = "John Peter";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mainSheet = ss.getSheetByName("MAIN");
var data = mainSheet.getDataRange().getValues();
for (var j = 0; j < data.length; j++){
var row = data[j];
var mainSheet2 = row[4];
var mainSheet3 = row[0];
var status = (mainSheet2 =="IN" && mainSheet3 == employee) ;
if (status == true){
var notify = employee +" You Are In"
return notify;
}
}
document.getElementById('status').innerHTML= notify;
}
</script>
<button onclick="onStatus()">Check Status</button>
<font color='Green' id="status" ></font>
</div>
Google provides a very good Client-to-Server Communication guide that I highly suggest you read to get a better understanding of how this works.
You cannot put apps script code (e.g. SpreadsheetApp.getActiveSpreadsheet()) in your frontend scripts. That code has to be run by the apps script server in the backend and you'll then call it using a google.script.run call.
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Index');
}
function checkStatus() {
var employee = "John Peter";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mainSheet = ss.getSheetByName("MAIN");
var data = mainSheet.getDataRange().getValues();
for (var j = 0; j < data.length; j++){
var row = data[j];
var mainSheet2 = row[4];
var mainSheet3 = row[0];
var status = (mainSheet2 =="IN" && mainSheet3 == employee) ;
if (status == true){
return employee + " You Are In";
}
}
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>
<button onclick="onStatus()">Check Status</button>
<font color='Green' id="status" ></font>
</div>
<script>
function onStatus() {
google.script.run
.withSuccessHandler(updateStatus) // Send the backend result to updateStatus()
.checkStatus(); // Call the backend function
}
function updateStatus(notify) {
document.getElementById('status').innerHTML= notify;
}
</script>
</body>
</html>
I'm trying to built an Orders system based on Google Spreadsheet.
I got 1 Spreadsheet ("Order") with 2 sheets ("Orders" and "Products").
First is totally blank (it'll be the sheets where my dialog will put data.
Second is a simple database with a list of articles:
Column A [ID]
Column B [BRAND]
Column C [PRODUCT]
Column D [PIECES]
Column E [PRICE]
Column F [CATEGORY]
Column G [UM]
Column H [VAT]
Column I [SUBCATEGORY]
One brand can have more than one product, in one or more category...
I got
1 Code.gs
and 4 HTML Dialogs
Scelta Categoria.html
Scelta Marchio.html
Scelta Prodotto.html
Ordini.html
Here I don't put Scelta Prodotto.html or Order.html code because first of all I need to pass data between the other dialogs.
I don't wanna a web app if it's possible, but a simple spreadsheet with my custom dialogs working.
I'm not searching for a spreadsheet shared with my costumers but more spreadsheet (every = at the other) one for every my costumer (is a little business, with only 30 costumers, and not all are able to use internet or pc to send me their orders (most of them used call me by phone and dictate me the order).
For them who are more modern as I'm, I start develop those (as Google call in his Script Guide) Scripts Bound to Google Sheets.
code.gs
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Ordine')
.addItem('Apri Maschera', 'ApriSceltaCategoria')
.addToUi();
//doGet();
ApriSceltaCategoria();
}
// Visualizza l'interfaccia grafica.
// Chiamata alla funzione "setRngProdotto()" per assicurare che tutti i nuovi valori sono inclusi nella dropdown list quando l'interfaccia รจ visualizzata.
function ApriSceltaCategoria() {
var ss;
var html;
setRngCat();
ss = SpreadsheetApp.getActiveSpreadsheet();
html = HtmlService.createHtmlOutputFromFile('Scelta Categoria').setSandboxMode(HtmlService.SandboxMode.IFRAME);
ss.show(html);
}
function ApriSceltaMarchio(CategoriaScelta) {
var ss;
var html;
setRngMarchi();
setRngCompleto();
ss = SpreadsheetApp.getActiveSpreadsheet();
html = HtmlService.createHtmlOutputFromFile('Scelta Marchio').setSandboxMode(HtmlService.SandboxMode.IFRAME);
ss.show(html);
}
function ApriSceltaProdotto(ProdottoScelto) {
var ss;
var html;
setRngProdotti();
setRngCompleto();
ss = SpreadsheetApp.getActiveSpreadsheet();
html = HtmlService.createHtmlOutputFromFile('Scelta Prodotto').setSandboxMode(HtmlService.SandboxMode.IFRAME);
ss.show(html);
}
// Chiamata dalla Client-side JavaScript nella pagina.
// Usa l'argomento del nome del range per estrarre i valori. I valori sono quindi ordinati e restituiti come un array di arrays.
function getValuesForRngName(rngName) {
var rngValues = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(rngName).getValues();
return rngValues.sort();
}
//Expand the range defined by the name as rows are added
function setRngCat() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('Prodotti');
var firstCellAddr = 'F2';
var dataRngRowCount = sh.getDataRange().getLastRow();
var listRngAddr = (firstCellAddr + ':F' + dataRngRowCount);
var listRng = sh.getRange(listRngAddr);
ss.setNamedRange('rngListaCategorie', listRng);
}
//Expand the range defined by the name as rows are added
function setRngMarchi() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('Prodotti');
var firstCellAddr = 'B2';
var dataRngRowCount = sh.getDataRange().getLastRow();
var listRngAddr = (firstCellAddr + ':B' + dataRngRowCount);
var listRng = sh.getRange(listRngAddr);
ss.setNamedRange('rngListaMarchi', listRng);
}
//Expand the range defined by the name as rows are added
function setRngProdotto() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('Prodotti');
var firstCellAddr = 'C2';
var dataRngRowCount = sh.getDataRange().getLastRow();
var listRngAddr = (firstCellAddr + ':C' + dataRngRowCount);
var listRng = sh.getRange(listRngAddr);
ss.setNamedRange('rngListaProdotti', listRng);
}
//Expand the range defined by the name as rows are added
function setRngCompleto() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('Prodotti');
var firstCellAddr = 'A2';
var dataRngRowCount = sh.getDataRange().getLastRow();
var listRngAddr = (firstCellAddr + ':I' + dataRngRowCount);
var listRng = sh.getRange(listRngAddr);
ss.setNamedRange('rngListaCompleta', listRng);
}
function OrdinaDati() {
setRngCat();
var rangeToSort = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('rngListaCategorie').getValues();
var selectionArray = rangeToSort.getValues();
rangeToSort.setValues(selectionArray.sort(ordinaLi));
setRngMarchi();
var rangeToSort = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('rngListaMarchi').getValues();
var selectionArray = rangeToSort.getValues();
rangeToSort.setValues(selectionArray.sort(ordinaLi));
setRngProdotto();
var rangeToSort = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('rngListaProdotti').getValues();
var selectionArray = rangeToSort.getValues();
rangeToSort.setValues(selectionArray.sort(ordinaLi));
setRngCompleto();
var rangeToSort = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('rngListaCompleta').getValues();
var selectionArray = rangeToSort.getValues();
rangeToSort.setValues(selectionArray.sort(ordinaLi));
}
function ordinaLi(a,b) {
// Sorts on the first column in the selection ONLY, ascending order.
a=a[0];
b=b[0];
return a==b?0:(a<b?-1:1);
}
/**
* Get the URL for the Google Apps Script running as a WebApp.
*/
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
/**
* Get "home page", or a requested page.
* Expects a 'page' parameter in querystring.
*
* #param {event} e Event passed to doGet, with querystring
* #returns {String/html} Html to be served
*/
function doGet(e) {
//Logger.log( Utilities.jsonStringify(e) );
Logger.log(e.parameter.page);
var pgToLoad = e.parameter.page;
if (!e.parameter.page) {
Logger.log('!e.parameter.page')
// When no specific page requested, return "home page"
return HtmlService.createTemplateFromFile('Scelta Categoria').evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Logger.log('there is something for the page');
// else, use page parameter to pick an html file from the script
return HtmlService.createTemplateFromFile('Scelta Categoria').evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Choose Category.html
<!DOCTYPE html>
<html style= "background-color:#B7CEEC;">
<head>
<base target="_top">
<p id="p_cat">Categoria scelta: - </p>
</head>
<body>
<title>TITOLO</title>
<div>
<form>
<hr>
<p style= "text-align: center;">Seleziona una <b style= "color:red;">CATEGORIA</b></p>
<hr>
<table id="Tabella">
</table>
<div style="text-align: center;">
<input type="button" style="font-size: 14px;" id="btnAvanti" value="Avanti -->"
onclick= "google.script.run.withSuccessHandler(google.script.host.close).ApriSceltaMarchio()" />
</div>
</form>
</div>
<hr>
<div style="float:right;">
<input type="button" value="Chiudi"
onclick="google.script.host.close()" />
</div>
<script type="text/javascript">
function estraicategorie (values) {
document.getElementById("btnAvanti").disabled = true;
var categorie = eliminaduplicati(values);
for (i = 0;i < categorie.length; i +=1) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var elemlabel = document.createElement('label');
strlabel = "" + categorie [i] + ""
elemlabel.innerHTML = strlabel.bold();
var eleminput = document.createElement('input');
eleminput.setAttribute('type', 'radio');
eleminput.setAttribute('name', 'categorie');
eleminput.setAttribute('value', categorie [i]);
td1.appendChild(elemlabel);
td2.appendChild(eleminput);
tr.appendChild(td1);
tr.appendChild(td2);
document.getElementById('Tabella').appendChild(tr);
}
var ch = document.getElementsByName('categorie');
for (var i = ch.length; i--;) {
ch[i].onchange = function() {
document.getElementById("btnAvanti").disabled = false;
document.getElementById("p_cat").innerHTML = "Categoria scelta: " + this.value;
}
}
}
function eliminaduplicati(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
function populate() {
google.script.run.withSuccessHandler(estraicategorie).getValuesForRngName('rngListaCategorie');
}
</script>
<script type="text/javascript">
// Using the "load" event to execute the function "populate"
window.addEventListener('load', populate);
</script>
</body>
</html>
Scelta marchio.html
<!DOCTYPE html>
<html style= "background-color:#B7CEEC;">
<head>
<base target="_top">
<p id="p_cat"></p><p id="p_mar"></p>
</head>
<body>
<title>TITOLO</title>
<div>
<form>
<hr>
<p style= "text-align: center;">Seleziona un <b style= "color:red;">MARCHIO</b></p>
<hr>
<table id="Tabella">
</table>
<div style="text-align: center;">
<input style="font-size: 14px;" type="submit" id="btnIndietro" value="<-- Torna>" onclick= "google.script.run.withSuccessHandler(google.script.host.close).ApriSceltaCategoria()" />
<input style="font-size: 14px;" type="submit" id="btnAvanti" value="Avanti -->" onclick= "google.script.run.withSuccessHandler(google.script.host.close).ApriSceltaProdotto()" />
</div>
</form>
</div>
<hr>
<div style="float:right;">
<input type="button" value="Chiudi" onclick="google.script.host.close()" />
</div>
<script type="text/javascript">
function estraimarchi (values) {
document.getElementById("btnAvanti").disabled = true;
var categoria = // HOW CAN I ACHIEVE THIS ???
var elencofiltratoXcat = [];
for (var i = 0; i < values.length; i +=1) {
if (values [i][5] === categoria) {
elencofiltratoXcat.push(values [i]);
}
}
var elencofiltratomarchi = [];
for (i = 0; i < elencofiltratoXcat.length; i +=1) {
elencofiltratomarchi.push(elencofiltratoXcat[i][1]);
}
var marchi = [];
marchi = eliminaduplicati(elencofiltratomarchi);
marchi.sort();
for (i = 0;i < marchi.length; i +=1) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var elemlabel = document.createElement('label');
strlabel = "" + marchi [i] + "";
elemlabel.innerHTML = strlabel.bold();
var eleminput = document.createElement('input');
eleminput.setAttribute('type', 'radio');
eleminput.setAttribute('name', 'marchi');
eleminput.setAttribute('value', marchi [i]);
td1.appendChild(elemlabel);
td2.appendChild(eleminput);
tr.appendChild(td1);
tr.appendChild(td2);
document.getElementById('Tabella').appendChild(tr);
}
var ch = document.getElementsByName('marchi');
for (var i = ch.length; i--;) {
ch[i].onchange = function() {
document.getElementById("btnAvanti").disabled = false;
document.getElementById("p_cat").innerHTML = "Categoria: " + categoria;
document.getElementById("p_mar").innerHTML = "Marchio: " + this.value;
}
}
}
function populate(){
google.script.run.withSuccessHandler(estraimarchi).getValuesForRngName('rngListaCompleta');
}
function eliminaduplicati(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
</script>
<script>
// Using the "load" event to execute the function "populate"
window.addEventListener('load', populate);
</script>
</body>
</html>
As I commented in the code, the problem is when I try to pass values between dialogs. I try to use in Scelta Categoria.html
document.getElementById("btnAvanti").disabled = false;
document.getElementById("p_cat").innerHTML = "Categoria scelta: " + this.value;
var userProperties = PropertiesService.getUserProperties();
var userCat = userProperties.setProperty('SceltaCategoria', '' + this.value + '');
but nothing to do.
Sure I can open another sheet and put user choice in A1 for example, then hide the sheet, but I reputate more quick if I can use variables.
Any suggestion, try to remain in this context and not in web app ?
Thanx in advance and sorry for my bad english.
I am working on an app development which will read through my mailbox and list all the unread e-mails in a HTML table on my web-app upon click of a button. Below is the code which I have made while researching through google which solves for the purpose.
<!DOCTYPE html>
<html>
<body>
<button onclick="groupFunction()">Click me</button>
<table id="tblContents">
<tr onclick="tableClickTest()">
<th>Sender</th>
<th>Sent_Date</th>
<th>Received_By</th>
<th>Received_Date</th>
<th>Subject</th>
</tr>
</table>
<script>
function RowSelection()
{
var table = document.getElementById("tblContents");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
}
function tableText(tableCell) {
alert(tableCell.innerHTML);
}
function PopulateTable()
{
var objOutlook = new ActiveXObject("Outlook.Application");
var session = objOutlook.Session;
//alert(session.Folders.Count)
for(var folderCount = 1;folderCount <= session.Folders.Count; folderCount++)
{
var folder = session.Folders.Item(folderCount);
//alert(folder.Name)
if(folder.Name.indexOf("Premanshu.Basak#genpact.com")>=0)
{
for(var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++)
{
var sampleFolder = folder.Folders.Item(subFolCount);
//alert(sampleFolder.Name)
if(sampleFolder.Name.indexOf("test1")>=0)
{
for(var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++)
{
var itm = sampleFolder.Items.Item(itmCount);
if(!itm.UnRead)
continue;
var sentBy = itm.SenderName;
var sentDate = itm.SentOn;
var receivedBy = itm.ReceivedByName;
var receivedDate = itm.ReceivedTime;
var subject = itm.ConversationTopic;
// var contents = itm.Body;
var tbl = document.getElementById("tblContents");
if(tbl)
{
var tr = tbl.insertRow(tbl.rows.length);
// tr.onclick(tableClickTest())
if(tbl.rows.length%2 != 0)
tr.className = "alt";
var tdsentBy = tr.insertCell(0);
var tdsentDate = tr.insertCell(1);
var tdreceivedBy = tr.insertCell(2);
var tdreceivedDate = tr.insertCell(3);
var tdsubject = tr.insertCell(4);
// var tdcontents = tr.insertCell(5);
tdsentBy.innerHTML = sentBy;
tdsentDate.innerHTML = sentDate;
tdreceivedBy.innerHTML = receivedBy;
tdreceivedDate.innerHTML = receivedDate;
tdsubject.innerHTML = subject;
// tdcontents.innerHTML = contents;
}
//itm.UnRead = false;
}
break;
}
}
break;
}
}
return;
}
function groupFunction()
{
PopulateTable()
RowSelection()
}
</script>
</body>
</html>
The thing that I am now looking for and is unable to do is how do I add a checkbox in the first column in each row. Also upon checking this checkbox the entire row should get highlighted so that I can perform specific task on all the selected items.
As far as I have understood your code, your first column's data is being set as:
tdsentBy.innerHTML = sentBy;
So in the same line, you can add textbox as a string as:
var cbox = "<div class='select-box'>
<input type='checkbox' name='selectBox' class='select-row'>
</div?>"
tdsentBy.innerHTML = cbox + sentBy;
In this way, a checkbox will always be available in first column of every row.
Now in RowSelection function, to bind event you can do something like:
var checkBox = table.rows[i].cells[j].querySelector(".select-row");
checkBox.addEventListener("click",function(evt){
});
I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview
This code appends an extra element to the first generated menus every time the function is called. The last element in each array is missing in all subsequent calls. I can't seem to figure out why this is happening.
<script type="text/javascript" language="javascript">
var elements = ['one','two','three','etc'];
var positions = ['Producer', 'Tech', 'Assist', 'Voice'];
function addNamelist() {
var q = document.createElement('select');
for (var j=0; j<positions.length; j++) {
q.setAttribute('id', positions[j]);
document.body.appendChild(q);
var r = document.createElement('option');
r.setAttribute('value', positions[j]);
var m = document.createTextNode(positions[j]);
r.appendChild(m);
document.getElementById(positions[j]).appendChild(r);
}
var y = document.createElement('select');
for (var i = 0; i < elements.length; i++) {
y.setAttribute('id', elements[i]);
document.body.appendChild(y);
var z = document.createElement('option');
z.setAttribute('value', elements[i]);
var t = document.createTextNode(elements[i]);
z.appendChild(t);
document.getElementById(elements[i]).appendChild(z);
}
}
</script>
</head>
<body>
<form action="editpageentry.php"><form>
create field
</body>
</html>