How function to return a variable? - javascript

I want to put number in the data type in html and use button to call the function to return the value to the variable.
function income(sumincome) {
var sumincome = 0
sumincome += parseInt(document.getElementById("income").value)
document.getElementById("resultin").innerHTML = (sumincome)
return sumincome;
}
function expenses() {
var sumexpenses = 0
sumexpenses += parseInt(document.getElementById("expen").value)
document.getElementById("resultexp").innerHTML = (sumexpenses)
return sumexpenses;
}
var net = income() - expenses();

that's very simple :
<!DOCTYPE HTML>
<html>
<body>
<script>
function income(sumincome) {
var sumincome = 10;
return sumincome;
}
function expenses() {
var sumexpenses = 5;
return sumexpenses;
}
var net = income() - expenses();
alert("Value Net : " + net);
</script>
</body>
</html>

Related

How to add conditionals to user input in App Scripts with while loops?

I made a selectBox which had its range of values from a Google Sheet Column. I also want to take an Integer input value from the user and then write this value in a specific cell according to option taken from selectBox. The html link does not show the integer response box. Is it possible to do the above plan in a while loop? Would appreciate any ideas and correction of code
function doGet() {
var ap = SpreadsheetApp.openByUrl("Gsheet URL here");
var ui = SpreadsheetApp.getUi();
var user = ui.prompt("Put down a number");
var result = result.getSelectedButton();
var sheet = ap.getSheetByName("lv");
var values = sheet.getRange("A2:A10").getValues();
var options = values.map(function(row)
{
#To show show the selected option??
var item = options.getSelecteditem();
if (item === A3)
{
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var a1 = cell.getA3Notation();
var val = cell.getValue();
SpreadsheetApp.getUi().alert("Ur value is "+a1+" value is "+val);
}
{
return '<option value="' + row[0] + '">' + row[0] + '</option>';
});
var html = '<form onSubmit="handleSubmit(this)"> Type of Cuisine' + options.join('') + '</select></form>';
return HtmlService.createHtmlOutput(html);
}
Using an Html Dialog to Control User Inputs
Not sure what you wanted so here's a complete example I whipped up for you.
Code.gs:
function processInput(obj) {
Logger.log(JSON.stringify(obj));
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
const [min,max,locs] = sh.getRange('B1:B3').getValues().flat();
Logger.log('min: %s max: %s locs: %s',min,max,locs)
const lA = locs.split(',');
if(obj.int > max) {
obj.msg = "Too High Try Again";
return obj;
} else if (obj.int < min) {
obj.msg = "To Low Try Again";
return obj;
} else if (!~lA.indexOf(obj.loc)) {
obj.msg = "Invalid Location";
return obj;
} else {
sh.getRange(obj.loc).setValue(obj.int);
obj.msg = "Complete";
return obj;
}
}
Following function Launches the dialog:
function launchInputDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'),"Enter Input");
}
html:
<!DOCTYPE html>
<html>
<head>
</head>
<style>input {margin: 2px 5px 2px 0;}</style>
<body>
<form>
<input type="text" id="in1" placeholder="Enter an integer" />
<br /><input type="text" id="in2" placeholder="Enter a location" />
<br /><input type="button" value="Process" onClick="processinput();" />
</form>
<div id="msg"></div>
<script>
function processinput() {
document.getElementById("msg").innerHTML = '';
let v1 = parseInt(document.getElementById('in1').value);
let v2 = document.getElementById('in2').value;
let obj = {int:v1,loc:v2,msg:''};
google.script.run
.withSuccessHandler(robj => {
console.log(JSON.stringify(robj))
if(robj.msg == "Complete") {
document.getElementById("msg").innerHTML = `Value: ${robj.int} Location: ${robj.loc} Try Again`;
document.getElementById("in1").value = '';
document.getElementById("in2").value = '';
} else {
document.getElementById("msg").innerHTML = robj.msg;
}
})
.processInput(obj);
}
</script>
</body>
</html>
Short Demo:
This version uses a <select> tag to allow the user to determine where the data will be loaded
GS:
function doPost(e) {
Logger.log(e.postData.contents);
Logger.log(e.postData.type);
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet1");
let data = JSON.parse(e.postData.contents);
sh.getRange(data.loc).setValue(data.id)
}
function sendData(obj) {
const url = ScriptApp.getService().getUrl();
const params = { "contentType": "application/json", "payload": JSON.stringify(obj), "muteHttpExceptions": true, "method": "post", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
UrlFetchApp.fetch(url, params);
}
function displayError(msg) {
SpreadsheetApp.getUi().alert(msg);
}
function launchMyDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'), 'My Dialog');
}
function getSelectOptions() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName('Options');
var rg = sh.getDataRange();
var vA = rg.getValues();
var options = [];
for (var i = 0; i < vA.length; i++) {
options.push(vA[i][0]);
}
return vA;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<input type="text" id="txt1" name="id" placeholder="Enter Numbers only"/>
<select id="sel1" name="loc"></select>
<input type="button" value="submit" onClick="processForm(this.parentNode);" />
</form>
<script>
function processForm(obj) {
console.log(obj.id.value);
if(obj.id.value.match(/[A-Za-z]/)) {
google.script.run.displayError("Invalid Characters Found in id field");
} else {
google.script.run.sendData(obj);
}
}
window.onload = function() {
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
}
function updateSelect(vA) {
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<vA.length;i++) {
select.options[i] = new Option(vA[i],vA[i]);
}
}
</script>
</body>
</html>
Demo:

JavaScript arrays adding last element instead of recently added input

Good evening. I am new to JavaScript and I need help with my mini-project and I have only one issue here and it is in the this.Add = function ().
It works properly when I enter a duplicate value from my list therefore it displays an alert that no dupes are allowed. But... when I enter a unique value, it only adds up the last element present (Wash the dishes) from myTasks list. instead of the one I recently entered and the list goes on adding the same ones. Did I just misplace something?
This is my final activity yet and I want to finish it to move to the next function. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tasks CRUD</title>
<style>
#tasks{
display: none;
}
</style>
</head>
<body>
<center>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-task" placeholder="Add another card">
<input type="submit" value="Add">
</form>
<div id="tasks" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-task">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Name</th>
</tr>
<tbody id="myTasks">
</tbody>
</table>
</center>
<script>
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
if (task ) {
for(task of this.myTasks)
{
var ctr = 0;
if(document.getElementById("add-task").value == task){
ctr = 1;
break;
}
}
if(ctr == 1)
{
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task.trim());
// Reset input value
el.value = '';
// Dislay the new list
this.FetchAll();
}
}
};
this.Edit = function (item) {
var el = document.getElementById('edit-task');
// Display value in the field
el.value = this.myTasks[item];
// Display fields
document.getElementById('tasks').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
// Get value
var task = el.value;
if (task) {
// Edit value
self.myTasks.splice(item, 1, task.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item) {
// Delete the current row
this.myTasks.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput() {
document.getElementById('tasks').style.display = 'none';
}
</script>
</body>
</html>
In your for loop:
for (task of this.myTask) {
}
You are not declaring a new task variable, but instead assigning to the outer task variable, hence the repeated addition of tasks already in your list.
You can declare a new variable in the for scope like so:
for (const task of this.myTask) {
}
Your HTML as it is.
And your Javascript goes like below. You have a bug while checking if the task already exists in the array. As you're comparing string value either use simple for loop with triple equals or do as i have attached below.
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
console.log(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
console.log(task);
if (task ){
var arrayContainsTask = (this.myTasks.indexOf(task) > -1);
if(arrayContainsTask == true){
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task);
// Reset input value
el.value = '';
}
// Dislay the new list
this.FetchAll();
}
}
}

javascript Uncaught TypeError: .indexOf is not a function

This is the javascript code:
/**
* Created by Alejandro on 25/02/2016.
*/
var aantalKoppels = 2;
function setup(){
var btnToevoegen = document.getElementById("btnToevoegen");
btnToevoegen.addEventListener("click", koppelToevoegen);
var btnReplace = document.getElementById("btnReplace");
btnReplace.addEventListener("click", update);
}
function koppelToevoegen() {
var parameterDataKoppel = document.createElement("div");
var labelParameter = document.createElement("label");
labelParameter.innerHTML = "Parameter:";
labelParameter.setAttribute("for", "parameter" + aantalKoppels);
var parameter = document.createElement("input");
parameter.id = "parameter" + aantalKoppels;
parameter.setAttribute("type", "text");
var labelData = document.createElement("label");
labelData.innerHTML = "Data:";
labelData.setAttribute("for", "data" + aantalKoppels);
var data = document.createElement("input");
data.id = "data" + aantalKoppels;
data.setAttribute("type", "text");
parameterDataKoppel.appendChild(labelParameter);
parameterDataKoppel.appendChild(parameter);
parameterDataKoppel.appendChild(labelData);
parameterDataKoppel.appendChild(data);
var parameterDataKoppels = document.getElementById("parameterDataKoppels");
parameterDataKoppels.appendChild(parameterDataKoppel);
aantalKoppels++;
}
function update() {
var parameterDataKoppels = [];
var rangnummerKoppel = 1;
for(var i = 0; i < aantalKoppels - 1; i++) {
var parameter = (document.getElementById("parameter" + rangnummerKoppel)).value;
var data = (document.getElementById("data" + rangnummerKoppel)).value;
parameterDataKoppels[i] = [parameter.trim(), data.trim()];
rangnummerKoppel++;
}
var template = document.getElementById("template");
vervangAlles(template, parameterDataKoppels);
}
function vervangAlles(template, parameterDataKoppels) {
for(var i = 0; i < parameterDataKoppels.length; i++) {
var result = vervang(template, parameterDataKoppels[i][0], parameterDataKoppels[i][1]);
template = result;
}
var output = document.getElementById("txtOutput");
output.innerHTML = template;
return template;
}
function vervang(template, parameter, data) {
var result = template.substring(0, template.indexOf(parameter)) + data;
var i = template.indexOf(parameter) + parameter.length;
while(template.indexOf(parameter, i) !== -1) {
var indexVolgende = template.indexOf(parameter, i);
result += (template.substring(i, indexVolgende)) + data;
i = indexVolgende + parameter.length;
}
result += template.substring(i, template.length);
return result;
}
window.addEventListener("load",setup,false);
This code should take a template (String), parameters (String word out of text) and data (String) as input to then replace al the parameters in the text by the String data. I do get an error which I can't figure out at the first line in the last function:
Uncaught TypeError: template.indexOf is not a functionvervang # ReplaceFunction.js:61vervangAlles # ReplaceFunction.js:52update # ReplaceFunction.js:47
this is the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" charset="utf-8" src="../scripts/ReplaceFunction.js"></script>
<title>ReplaceFunction</title>
</head>
<body>
<div>
<label for="template">Template:</label>
<input id="template" type="text" />
</div>
<div id="parameterDataKoppels">
<div>
<label for="parameter1">Parameter:</label>
<input id="parameter1" type="text" />
<label for="data1">Data:</label>
<input id="data1" type="text" />
</div>
</div>
<input id="btnToevoegen" type="button" value="Koppel toevoegen" />
<input id="btnReplace" type="button" value="Replace" />
<p id="txtOutput">geen output</p>
</body>
</html>
I hope somebody knows why I get this error.
It seems like your 'update' should be
function update() {
var parameterDataKoppels = [];
var rangnummerKoppel = 1;
for(var i = 0; i < aantalKoppels - 1; i++) {
var parameter = (document.getElementById("parameter" + rangnummerKoppel)).value;
var data = (document.getElementById("data" + rangnummerKoppel)).value;
parameterDataKoppels[i] = [parameter.trim(), data.trim()];
rangnummerKoppel++;
}
//var template = document.getElementById("template");
var template = document.getElementById("template").value;
vervangAlles(template, parameterDataKoppels);
}

Javascript flow control glitch

UPDATE: SOLVED! line 116 (ERROR3) had to be changed from 'parseInst(rom[i]); ' to 'rom[i]; '.
I'm working on an assembly simulator in Javascript. For some reason the JUMP instruction messes up the register contents. The following program (can be copy-pasted) increments register 'A' (0-->1) then jumps to instruction 0. Instead of '1', the register's content becomes a value over 5000. What am I doing wrong? UPDATE: added three errors caught by the debugger ("Uncaught RangeError: Maximum call stack size exceeded").
var regA = 0;
var regB = 0;
var accu = 0;
var rom = [];
var instCount = 0;
var flag1 = 0;
var stopState = 0;
function eval() {
var inst = document.getElementById("text_f").value;
parseInst(inst);
};
function parseInst(instString) {
if (instString.includes("LDA")) { //ERROR1
var strSplitA = instString.split(":");
regA = parseInt(strSplitA[1]);
document.getElementById("regA").innerHTML = regA;
instCount++;
document.getElementById("demo").innerHTML = "load register A: " + strSplitA[1]+"type of: "+typeof regA;
} else if (instString.includes("LDB")) {
var strSplitB = instString.split(":");
document.getElementById("demo").innerHTML = "load register B: " + strSplitB[1];
regB = parseInt(strSplitB[1]);
document.getElementById("regB").innerHTML = regB;
instCount++;
} else if (instString == "ADD") {
accu = regA + regB;
document.getElementById("demo").innerHTML = "add " + regA + "+" + regB + "=" + accu;
document.getElementById("accu").innerHTML = accu;
instCount++;
} else if (instString.includes("JMP")) {
var jumpTo = instString.split(":");
instCount = parseInt(jumpTo[1]);
document.getElementById("demo").innerHTML = "jump to: " + instCount+" typeof: "+typeof instCount;
document.getElementById("count").innerHTML = instCount;
runStop(stopState,parseInt(jumpTo[1])); //ERROR2
} else if (instString == "CMP") {
if (regA === regB) {
flag1 = 1;
instCount++;
document.getElementById("flag1").innerHTML = 1;
document.getElementById("demo").innerHTML = "flag1 set to 1";
} else {
flag1 = 0;
instCount++;
document.getElementById("flag1").innerHTML = 0;
document.getElementById("demo").innerHTML = "flag1 set to 0";
};
} else if (instString.includes("INC")) {
var incRegister = instString.split(":");
switch (incRegister[1]) {
case "A":
regA++;
document.getElementById("demo").innerHTML = "case A";
document.getElementById("regA").innerHTML = regA;
instCount++;
break;
case "B":
regB++;
document.getElementById("demo").innerHTML = "case B";
document.getElementById("regB").innerHTML = regB;
instCount++;
break;
default:
document.getElementById("demo").innerHTML = "error: register name";
break;
}
} else {
document.getElementById("demo").innerHTML = "error: no instruction";
};
};
function saveToRom() {
var romString = document.getElementById("text_f").value;
rom = romString.split(",");
document.getElementById("rom").innerHTML = rom;
document.getElementById("demo").innerHTML = "#debug:save to rom";
reset();
};
function step() {
parseInst(rom[instCount]);
document.getElementById("count").innerHTML = instCount-1;
};
function run() {
stopState = 0;
document.getElementById("demo").innerHTML = "run";
runStop(stopState,instCount);
};
function stop(){
stopState = 1;
document.getElementById("demo").innerHTML = "stop";
runStop(stopState,instCount);
};
function runStop(stopSt,instructionCount){
if(stopSt == 0){
for(var i=instructionCount;i<rom.length;i++){
parseInst(rom[i]); //ERROR3
document.getElementById("demo").innerHTML = "#runStop(): stopState: "+stopState+" for loop length: " + rom.length;
}
} else {
document.getElementById("demo").innerHTML = "#runStop(): stopState: "+stopState;
};
};
function reset() {
document.getElementById("demo").innerHTML = "debug: reset";
regA = 0;
regB = 0;
accu = 0;
flag1 = 0;
instCount = 0;
document.getElementById("regA").innerHTML = regA;
document.getElementById("regB").innerHTML = regB;
document.getElementById("accu").innerHTML = accu;
document.getElementById("count").innerHTML = instCount;
document.getElementById("flag1").innerHTML = flag1;
};
The full source code with HTML on Github.
I appreciate your help in advance! EDIT: The html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>COMPU</title>
<script type='text/javascript' src='comp3.1.js'></script>
<link rel="stylesheet" type="text/css" href="stylesheet_comp.css">
</head>
<body>
<input type="text" id="text_f" value=" " autofocus>
<br><br>
<div class="nav">
<button onclick="eval()">EXEC</button>
<button onclick="saveToRom()">SAVE</button>
<button onclick="reset()">RST</button>
<button onclick="step()">STEP</button>
<button onclick="run()">RUN</button>
<button id="stop" value=0 onclick="stop()">STOP</button>
</div>
<br>
<div class="displays">
DEBUG:
<p id="demo">*debugging messages*</p>
REG A:
<p id="regA">0</p>
REG B:
<p id="regB">0</p>
ACCU:
<p id="accu">0</p>
<br> ROM:
<p id="rom"></p>
INS COUNT:
<p id="count">0</p>
FLAG1:
<p id="flag1">0</p>
<!--
DEBUG2:
<p id="dbg2"></p>
-->
</div>
INSTRUCTIONS:
<ol>
<li>ADD</li>
</ol>
</body>
</html>
UPDATE: SOLVED! line 116 (ERROR3) had to be changed from 'parseInst(rom[i]); ' to 'rom[i]; '.

output as undefined/NAN

Would anyone clerify why my program is outputting undefined or NAN? I know for sure that my random number generator is working. Also, I'm trying to sum up all of the "score" value when the number generator has generated the value 10 times. Thanks for the help
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score;
var number;
number = randomnumber()
for (n=0;n<11; n=n+1)
{
if (number==0)
{
score =score+0
}
if (number==2)
{
score =score+2
}
if (number==3)
{
score =score+3
}
document.write(score)
}
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
Because score variable is undefined. You should initialize it with a number for instance: var score = 0;
Variable score is declared in your totalscore function but never initialised. Adding anything to undefined gives NaN, which is what your function writes to the page.
You need to initialize your score variable with 0. Until you don't, it's value is undefined and when you do math operations on an undefined object, you wil get a NaN error. I have also formatted your code a bit.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score = 0;
var number = randomnumber();
for (n = 0 ; n < 11 ; ++n)
{
if (number == 0){
score += 0;
}
else if (number == 2)
{
score += 2;
}
else if (number == 3)
{
score += 3;
}
document.write(score)
}
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
EDIT: If I understand your comment correctly, you should be doing something like this
function totalscore()
{
var n;
var score = 0;
for (n = 0 ; n < 10 ; ++n)
{
score += randomnumber();
document.write(score)
}
var grandTotal = score;
}

Categories

Resources