Sum of form input in Javascript - javascript

I want the user to enter a number then when it is submitted, it is inserted into the array totalBags.
The user can then submit another number, when submitted the array elements are added together.
E.g. Input = 2
Press submit
Output = 2
New input = 3
Press submit
Output = 5
Here is my code:
<html>
<head>
<script type = "text/javascript">
function submitOrder()
{
var allBags = [];
var bags_text = document.getElementById("bags").value;
allBags.push(bags_text);
var totalBags = 0;
for (var i = 0; i < allBags.length; i++)
{
totalBags += allBags[i]; // here is the problem... i think
}
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
function resetOrder()
{
document.getElementById("container").innerHTML = "<p><label for=\"bags\">No. bags: </label><input type=\"text\" id=\"bags\" /></p><p><input type=\"button\" value=\"Subit order\" onClick=\"submitOrder()\"> <input type=\"reset\" value=\"Reset Form\" /></p>";
}
</script>
</head>
<body>
<form name="order_form" id="order_form">
<div id="container">
<label>Total bags: </label><input id="bags" type="text" ><br>
<input type="button" id="submitButton" value="Subit order" onClick="submitOrder()">
<input type="reset" value="Reset" class="reset" />
</div>
</form>
</html>

I should rewrite the program a bit. First, you can define global variables which won't be instantiated in the function. You are doing that, which resets the variables. Fe
function submitOrder()
{
var allBags = [];
// ...
}
It means that each time you're clicking on the button allBags is created as a new array. Then you add an value from the input element. The result is that you have always an array with one element. It's best to declare it outside the function. By this, you ensure that the variables are kept.
// general variables
var allBags = [];
var totalBags = 0;
function submitOrder()
{
// the result is a string. You have to cast it to an int to ensure that it's numeric
var bags_text = parseInt(document.getElementById("bags").value, 10);
// add result to allBags
allBags.push(bags_text);
// total bags
totalBags += bags_text;
// display the result
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
by leaving out the loop, you have an more performant program. But don't forget to clear the array and the totalBags variable to 0 if you're using the reset button.
function resetOrder()
{
document.getElementById("container").innerHTML = "...";
// reset variables
totalBags = 0;
allBags = [];
}

Try to use:
for (var i = 0; i < allBags.length; i++)
{
totalBags += parseInt(allBags[i],10);
}
Or use Number(allBags[i]) if you prefer that.
Your element allBags[i] is a string and + between strings and concatenting them.
Further study: What is the difference between parseInt(string) and Number(string) in JavaScript?

function submitOrder()
{
var allBags = parseInt(document.getElementById("bags").value.split(""),10);//Number can also used
var totalBags = 0;
for (var i = 0; i < allBags.length; i++)
{
totalBags += allBags[i];
}
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}

Related

Function to Search for a Specified Value Within an Array?

I am fairly new to JavaScript and StackOverflow and am currently trying to create a function to search for a specialized value within a created array. I have written out what seems like a function that would work, any ideas or any obvious flaws in it? It is currently not working. Thanks!
HTML:
<td>Index: <input style = "width: 50px" input type ="textbox" id="Index" value="2"/></td> <!-- HTML code to create the index textbox -->
<br/> <!-- Line Break -->
Value: <input style = "width: 50px" input type = "textbox" id="Value" value = "10"/> <!-- HTML code to create the value textbox -->
<br />
<td>Enter Value to Find: <input style="width: 50px;" type="textbox" value="20" />
<input type="button" value="Search Array" onClick = searchArray(); /></td>
<br />
<input type = "button" value = "Create" onClick = "createArray();"/>
<input type="button" value="Insert into Array" onClick="insertIntoArray();" />
<div id="result">
JS:
var myArray = [];
var d = ""; //This global variable is going to be used for clearing and populating the screen
function createArray (){
//This functions is to clear the current information on the screen so the array can populate
clearScreen();
//The next thing we want to do according to the lecture is create a FOR loop to run 100 times to set the various array values
for (var i = 0; i <100; i++){
myArray[i] = Math.floor(Math.random()* 100 + 1); //Math.floor rounds an number downards to the nearest integer then returns. Math.random returns a integer randomly withing given variables
}
popScreen(); //function to fill the screen with the array
}
function clearScreen(){
d = ""; //Global string variable mentioned before
document.getElementById("result").innerHTML = "";
}
function popScreen(){
for (var i = 0; i < myArray.length - 1; i++){
d += i + ' : ' + myArray[i] + "<br/>";
}
document.getElementById("result").innerHTML = d;
}
function insertIntoArray(){
clearScreen();
var i= parseInt(document.getElementById("Index").value);
var j = parseInt(document.getElementById("Value").value);
d = "inserting " + j+ " at " + i + "<br/>";
var temp = myArray[i];
for (i; i < 100; i++) {
myArray[i] = j;
j = temp
temp = myArray[i+1];
}
popScreen();
}
**function searchArray(myArray, value){
var searchResult = 0;
var searchIndex = -1;
for(var i = 0; i<myArray.length; i++){
searchResult++;
if(myArray[i] == value){
searchIndex = i;
break;
}
}
if (searchIndex == -1){
console.log("Element inquiry not found in array. Total Searched: " + searchResult);
}else{
console.log("Element found at index: " + searchIndex + ", search count: " + searchResult);
}**
}
The issue is caused by the fact there are no arguments passed to the searchArray function via the inline onclick attribute... And they are necessary.
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
The error thrown is because myArray is undefined and therefore has no length property.
To have it working, I would modify the HTML from:
<input type="button" value="Search Array" onClick = searchArray(); />
to:
<input type="button" value="Search Array" onClick = searchArray(this); />
And the function would change like this:
function searchArray(element) {
let value = element.previousElementSibling.value
// rest unchanged
searchArray being already defined at global scope, you don't need to pass it.
But you need the value from the input right before the button. You can get it using previousElementSibling.

Using The Input Value Instead Of The First Statement Of A Loop In JavaScript

I am trying to understand the insertion sort algorithm. I want to use an input button and diagram. When the user writes a number then click the button, my page will create random values. I found some snippets on the internet but they use i = 0. I want to use my input value instead of i = 0. How can I do it?
A part of my index.html:
<div id="buttons">
<a class="button" id="butonInsert" href="javascript://">insertion sort</a>
<a class="button" id="butonReset" href="javascript://">Reset</a>
<input type="number" id="myNumber" value="blabla">
<button onclick="reset()"></button>
A part of my script.js:
function reset() {
for (i=0; i<50; ++i) {
data[i] = ~~(i*160/50);
}
for (i=data.length-1; i>=0; --i) {
var ridx = ~~( Math.random() * ( data.length ) );
data.swap(i, ridx);
}
var tb = $("#sortPanel");
tb.empty();
var tr = $("<tr></tr>");
for (i=0; i<data.length; ++i) {
tr.append("<td id='b"+i+"'>" +
"<div class='cc' style='height: "+data[i]+"px;'>" +
"</div></td>");
}
tb.append(tr);
resetted = true;
}
I didn't quite understand what you are trying to do but if you just want to use an input's value you can easily get it with javascript and use it instead of i=0.
var inputValue = document.getElementById("myNumber").value ;
Then in your for statements :
for (var i = inputValue ; i < data.length; ++i) {
// code
}
Use document.getElementbyId('myNumber').value. This might work.

Javascript array return "a"?

I wrote this piece with expectancy to store name and score in each and every array element.
Expected output:
var students = [
['David', 80],
['Dane', 77],
['Dick', 88],
['Donald', 95],
['Dean', 68]
];
However, I stumble upon assigning the second value in an array element... In codepen.io, the value returned is "a".
HTML:
name: <input type="text" id="namebox"><br><br>
score: <input type="text" id="scorebox"><br><br>
<input type="button" value="Add" onclick="addStudent()">
<input type="button" value="Display" onclick="displayArray()">
Javascript:
var x = 0;
var students = [];
function addStudent(){
students[x] = document.getElementById("namebox").value;
students[x][1] = document.getElementById("scorebox").value;
alert(students[x] + " added");
x++;
document.getElementById("namebox").value = "";
document.getElementById("scorebox").value = "";
document.getElementById("namebox").focus();
document.getElementById("scorebox").focus();
}
function displayArray(){
var e = "<hr>";
for (y = 0; y < students.length; y++)
{
e += students[y] + students[y][1] + "<br>";
}
document.getElementById("result").innerHTML = e;
}
as suggested by #Y.C. if you add students[x][0] = document.getElementById("namebox").value; your code will work. I wanna propose just a minor modification though so that your json array keeps its "pattern". Enclose document.getElementById("scorebox").value in parseInt() so you get the score as a number. In other words just write parseInt(document.getElementById("scorebox").value);
UPDATE
since my previous suggestion only works if you predefine the array I editted the code so now this should work.
instead of assigning the value to each cell I used push() function so now the addStudent method looks like this:
function addStudent(){
students.push(document.getElementById("namebox").value, parseInt(document.getElementById("scorebox").value));
alert(students[x] + " added");
x++;
document.getElementById("namebox").value = "".focus();
document.getElementById("scorebox").value = "".focus();
document.getElementById("namebox").focus();
document.getElementById("scorebox").focus();
}
UPDATE #2
my last update was only for addStudent to work since I thought this was the problem. So now this whole thing has to work by following the steps below:
on your html add a div with the id result because it seems that you forgot
<div id="result"></div>
on your Javascript just copy and paste the following
var x = 0;
var students = [];
function addStudent(){
students.push([document.getElementById("namebox").value, parseInt(document.getElementById("scorebox").value)]);
alert(students[x] + " added");
x++;
document.getElementById("namebox").value = "".focus();
document.getElementById("scorebox").value = "".focus();
document.getElementById("namebox").focus();
document.getElementById("scorebox").focus();
}
function displayArray(){
var e = "<hr>";
for (y = 0; y < students.length; y++)
{
e += students[y][0] + " " + students[y][1] + "<br>";
}
document.getElementById("result").innerHTML = e;
}
Notice that I have changed the addStudent function a bit just to add every student as a seperate array consisted of his/her name and his/her score.
do something like this
function addStudent(){
var studentArray = [],
tempArray = [],
index= 0;
tempArray[0] = document.getElementById("namebox").value; // David
tempArray[1] = document.getElementById("scorebox").value; //80
// this will insert array into main array.
studentArray.push(tempArray); // [['David', 80]]
// rest of your code
return studentArray;
}

Converting form text in HTML into an array in JS

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

Javascript: Read, Add and Display form values

I am trying to write a web app that takes user input as numbers in 15 text or number inputs on a html form, it should then add these values together and display the total in a label elsewhere on the page.
I have 15 inputs with the class name "takings" and a label with the ID "TotalLabel" on the page.
function getsum () {
var rows = document.getElementsByClassName("takings");
var total = 0;
for (var i = 0; i < rows.length; i++) {
var val = parseFloat(rows[i].value);
total += val;
}
var label = document.getElementById("TotalLabel");
label.value = total;
alert(parseFloat(total));
}
window.onload = getsum;
The alert is only in place for debugging purposes and it appears that the variable total is still set to zero at the end of the script. I also need to make the getsum() function fire every time a user enters data in any of the fields with class "takings".
Can anyone help?
So you need to add change events to all of the elements and call getsum
function getsum () {
var rows = document.getElementsByClassName("takings");
var total = 0;
for (var i = 0; i < rows.length; i++) {
var val = parseFloat(rows[i].value);
total += val;
}
var label = document.getElementById("TotalLabel");
label.value = total;
}
window.onload = getsum;
//Example showing how to add one event listener to the page and listen for change events
//The following works in modern browsers, not all browsers support addEventListener, target, and classList.
document.body.addEventListener("change", function(evt) {
var targ = evt.target;
if(targ.classList.contains("takings")) {
getsum();
}
});
label { display: block; }
<label>1</label><input type="text" class="takings" value="0"/>
<label>2</label><input type="text" class="takings" value="0"/>
<label>3</label><input type="text" class="takings" value="0"/>
<label>4</label><input type="text" class="takings" value="0"/>
<label>5</label><input type="text" class="takings" value="0"/>
<label>Total:</label><input type="text" id="TotalLabel" value="0" readonly/>
To have your getSum() function fire for all of those elements, you can use Javascript to add an onchange event to all elements with the required class name
var input = document.getElementsByClassName("takings");
for (var i = 0; i < cells.length; i++) {
input[i].onchange = getSum;
}
Other than that, I don't see any visible errors in your getSum() function.
You need to add an EventListener to your input fields and call getsum, for example
var a = document.getElementsByClassName("takings");
for (var i = 0;i<a.length;i++){
addEventListener('keyup',getsum);
}
Please note that a label has innerHTML, not a value:
label.innerHTML = total;
With your actual function, you will get NaN as a result as long as not all the inputs have a value, so you will need to add
if (val) {
total += val;
}
to your for loop.
Full working code:
function getsum(){
var rows = document.getElementsByClassName("takings");
var total = 0;
for (var i =0; i < rows.length; i++){
var val = parseFloat(rows[i].value);
if (val) {
console.log(val);
total += val;
}}
var label = document.getElementById("TotalLabel");
label.innerHTML = total;
}
var a = document.getElementsByClassName("takings");
for (var i = 0;i<a.length;i++){
this.addEventListener('keyup',getsum);
}
DEMO

Categories