JavaScript value won't insert into HTML input box with getElementById method - javascript

I am attempting to set up a very basic webpage which essentially documents various coding challenges I have completed.
I am currently attempting to take a value out of JavaScript and place it into an input box in HTML. I understand the usage of innerHTML and getElementById (and I have used both of them before to input a value into a text box) but it seems that I am missing something this time around. I can't seem to get the new value of "sum" to show in the text box.
What am I doing that is incorrect? Is the value of "sum" getting lost in the for / if statement? I apologize if this is overly simple. I cannot find anything that makes this work.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var sum = 0;
for (i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum = sum += i;
}
}
var totalSum = sum;
getElementById("answer1").innerHTML = totalSum;
</script>
<h1>Challenge 1</h2>
<p>Find the sum of all the multiples of 3 or 5 below 1000 (begin with 10, then work up).</p>
<p>Answer is
<input type="text" id="answer1"></input>
</p>
</body>
</html>

input is a single tag element, it cannot have inner HTML. Set the value property instead. Also it's document.getElementById, not just getElementById.
document.getElementById("answer1").value = totalSum;
You should also either put the script below the element or attach it to the window.onload.
<script>
window.addEventListener('load', function () {
var sum = 0;
for (i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum = sum += i;
}
}
var totalSum = sum;
document.getElementById("answer1").value = totalSum;
});
</script>

<!DOCTYPE HTML>
<html>
<head>
<title> Untitled </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style type="text/css">
textarea {
overflow: auto;
}
</style>
</head>
<body>
<h1>Challenge 1</h2>
<p>Find the sum of all the multiples of 3 or 5 below 1000 (begin with 10, then work up).</p>
<p>Answer is
<input type="text" id="answer1"></input>
</p>
<script type="text/javascript">
$(document).ready(function(){
var sum = 0;
for (i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum = sum += i;
}
}
console.log(sum);
var totalSum = sum;
console.log(totalSum);
document.getElementById("answer1").value = sum;
});
</script>
</body>
</html>

You need to call the getElementById on the document object. Additionally, you are wanting to set the input property, not the innerHTML.
document.getElementById("answer1").value = totalSum;
See example

I could swear it's document.getElementById not just getElementById
Also, try putting your JavaScript at the bottom. You're trying to manipulate an element on the page that hasn't yet been rendered.

var sum = 0;
for (i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum = sum += i;
}
}
var totalSum = sum;
document.getElementById("answer1").value = totalSum;
The reason is because you are using the innerHTML property instead of the value property. Input does not have the innerHTML property unlike other DOM elements because it's a single tag element. Also, you have a syntax error : it's document.getElementById not just getElementById.
Here's a working fiddle

Related

Get text from each element with certain class and then add up

I'm trying to do some calculations using javascript. I'm basically getting the text of each element with a certain class, convert that to a number and then add those numbers up.
This is what I've got so far:
<p class="item-size">1000</p>
<p class="item-size">2000</p>
JS:
$(document).ready(function(){
var elements = document.getElementsByClassName("item-size");
var size = ''
for (var i=0; i<elements.length; i++) {
size += parseInt((elements[i].innerText).replace(/[^0-9.]/g, ""));
}
console.log(size);
});
This returns 10002000 in the console. However, I need to get each of those values and then add them up instead of displaying them as one number. So the result should be 3000.
I've tried this:
var myTotal = 0;
for(var i = 0, len = size.length; i < len; i++) {
myTotal += size[i][1];
console.log(myTotal);
}
However, this returns NaN. Any ideas how to do this?
You need a number as target variable.
$(document).ready(function(){
var elements = document.getElementsByClassName("item-size");
var size = 0; // <-- zero instead of an empty string
for (var i=0; i<elements.length; i++) {
size += parseInt((elements[i].innerText).replace(/[^0-9.]/g, ""), 10); // take base
}
console.log(size);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="item-size">1000</p>
<p class="item-size">2000</p>
var size = 0, when you add string with integer it will return string and calculated as string. int + str = str
Here's ES5 version:
const elements = document.getElementsByClassName("item-size");
const size = Object.keys(elements)
.reduce((acc, curr) =>
acc + parseInt(elements[curr].innerText.replace(/[^0-9.]/g, "")), 0)
console.log(size);
https://jsfiddle.net/becg3vqu/3/
Loop through all the children of an element and for each one increment a number by the textcontent of the element with a unary operator.
function getSumOfClass(className, root) {
if (!(root instanceof HTMLElement)) root = document.body;
return [].reduce.call(root.querySelectorAll("." + className),
(result, dom) => result + (+dom.textContent || 0), 0);
}
console.log(getSumOfClass("item-size"));
<p class="item-not-size">500</p>
<p class="item-size">1000</p>
<p class="item-size">2000</p>
Adding a + or a - infront of a parameter or literal will convert it to a number. If it can't be converted to a number, the result will be NaN so you can just add an || operator to return a 0 in that case (so that the non arithmetic value will be ignored).
Using javascript vanilla
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p class="item-size">1000</p>
<p class="item-size">2000</p>
<script>
//getting the texts that contain numbers
let items = document.getElementsByClassName("item-size");
let sum = 0;
//Now for each element in the arrays
for (let i = 0; i < items.length; i++) {
sum = sum + parseInt(items[i].innerText);
}
console.log(sum);
</script>
</body>
</html>
Since size is initially an empty string the addition wont work as you expected. Initialize var size to 0.

How to use variables in for loop statements in javascript?

So I'm trying to get this to roll an amount of dice equal to the specified input. To achieve this, I'm using a for loop, however it's not working.
As I just started coding recently, I have no idea why. Could someone please help?
<!DOCTYPE html>
<html>
<body>
<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display"></p>
<script>
var random = [];
document.getElementById("display").innerHTML = random;
a = document.getElementById("diceamount").innerHTML;
function FirstFunction() {
for (i=0; i<"a"; i++) {
x = Math.floor(Math.random() * 4) + 1;
random.push(x);
document.getElementById("display").innerHTML = random;
}
}
</script>
</body>
</html>
Here is how you could do it. There are several issues highlighted in comments:
function FirstFunction() {
// Reset array within this function
var random = [];
// Get value property, and convert to number (with +)
// And use var!
var a = +document.getElementById("diceamount").value;
// No quotes around a, and use var!
for (var i=0; i<a; i++) {
// Use var!
var x = Math.floor(Math.random() * 4) + 1;
random.push(x);
}
// Only show after the loop, and use textContent
document.getElementById("display").textContent = random;
}
<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display"></p>
Note that the array gets implicitly formatted as a comma separated value string when you display it.
This is not how you define "a".
This is how you do it:
for (i=0; i<a; i++) {
This is how you get the value from the text field:
var b = document.getElementById('textbox_id').value;
Then get the integer value:
var a = parseInt(b);
And then the for loop:
for (i=0; i<a; i++) {
It seems you are doing it wrong ,...
Suppose you want to take the value of input which has id = "diceamount"
so for that you have to store the value of the input in variable.
var a = document.getElementById('diceamount').value;
for(i = ; i<= a; i++){
your code
}
make this question down ; and look for some tutorials for javascript
var random = [];
// not useful? but in your code
document.getElementById("display").innerHTML = random;
function FirstFunction(event) {
// get local value into a and use it the + avoids parseInt
let a = Math.abs(+document.getElementById("diceamount").value);
for (i=0; i<a; i++) {
// x was not declared and should be
let x = Math.floor(Math.random() * 4) + 1;
random.push(x);
}
// could be textContent instead...outside loop
document.getElementById("display").innerHTML = random;
}
<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>
<p id="display">x</p>

JS: innerHTML inconsistency

I am using Google Chrome version 43.0.2357.130. I am trying to append output to an HTML element using innerHTML, which is being done inside of a loop. I get the expected result most of the time, but if I click on the "Generate" button over and over, eventually it will give me an unexpected result. For instance, one of the passwords will be chopped off at a random spot. I used the JS debugger in Chrome, but that didn't help much. Then I tried to debug it myself by using the alert() function alongside the innerHTML property so that I could compare the output. The output in the alert() popup was never truncated, unlike innerHTML.
I highlighted what I think is the problem code with '/* PROBLEM CODE */' in the JS file. The files should be placed in the same directory. Here is the HTML and JS:
<!DOCTYPE html>
<html>
<head>
<title>PassGen - Random Password Generator</title>
<!--link rel="stylesheet" src="//normalize-css.googlecode.com/svn/trunk/normalize.css"-->
<!--link href="css/main.css" rel="stylesheet" type="text/css"-->
<!--script src="../app/js/jquery-2.1.4.js"></script-->
</head>
<body>
<form>
<h2>Password amount</h2>
<input type="text" id="amount" name="amount" />
<h2>Letter amount</h2>
<input type="text" id="letters" name="letters" />
<h2>Number amount </h2>
<input type="text" id="numbers" />
<h2>Symbol amount</h2>
<input type="text" id="symbols" />
<input onclick="generatePassword(); return false;" type="submit" value="Generate" />
</form>
<p id="output"></p>
<script src="plain-app.js"></script>
</body>
</html>
// get the DOM element we will be using for the final output
var output = document.getElementById("output");
function generatePassword(amount) {
clearPasswords();
// get DOM form elements (user input)
var amount = document.getElementById("amount").value;
var letters = document.getElementById("letters").value;
var numbers = document.getElementById("numbers").value;
var symbols = document.getElementById("symbols").value;
// populate character sets
var letterSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numberSet = "0123456789";
var symbolSet = "~!##$%^&*()-_+=><";
var array = [];
// if there is no password amount specified, create one password
if(amount === undefined) {
amount = 1;
}
for(var j = 0; j < amount; j++) {
// random character sets to be concatenated later
var rl = "";
var rn = "";
var rs = "";
var tp = ""; // concatenated password before shuffling
// 3 random letters
for(var i = 0; i < letters; i++) {
var rnd = Math.floor((Math.random() * 52));
rl += letterSet[rnd];
}
// 3 random numbers
for(var i = 0; i < numbers; i++) {
var rnd = Math.floor((Math.random() * 10));
rn += numberSet[rnd];
}
// 3 random symbols
for(var i = 0; i < symbols; i++) {
var rnd = Math.floor((Math.random() * 17));
rs += symbolSet[rnd];
}
tp = rl + rn + rs; // string concatentation
tp = tp.split(''); // transform string into an array
// shuffling
for(var i = 0; i < tp.length; i++) {
var rnd = Math.floor(Math.random() * tp.length);
var temp = tp[i];
tp[i] = tp[rnd];
tp[rnd] = temp;
}
// transform the array into a string
tp = tp.join("");
array[j] = tp; // for logging and debugging purposes
// tp can be replaced with array[j], but still get the inconsistency
/* PROBLEM CODE */
output.innerHTML += (tp + "<br />");
/* PROBLEM CODE */
//alert(array[j]);
}
console.log(array);
return array; // not useful?
}
// clear all password output
function clearPasswords() {
while(output.hasChildNodes()) {
output.removeChild(output.firstChild);
}
}
Does innerHTML have side effects I don't know about or am I using it incorrectly? Should it not be used for appends? Should appendChild() be used instead?
The problem is that some characters have special meaning in HTML: <, >, &.
Therefore, you can
Remove those characters from the list
Escape them: <, >, &
output.innerHTML += tp.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&') + "<br />";
Parse the text as text instead of as HTML, e.g.
Use textContent and white-space
output.textContent += tp + "\n";
#output { white-space: pre-line; }
Use createTextNode and appendChild
output.appendChild(document.createTextNode(tp));
output.appendChild(document.crateElement('br'));
The problem occurred in the symbolSet. It contained the characters < and >. When they were selected at random and added to the password, the browser tried to render them as elements when I was outputting the password to the screen. To fix this, I just removed the two characters from symbolSet, and changed the random symbol generation loop to reflect the shortened length of symbolSet.
I changed the two problematic sections of code to
var symbolSet = "~!##$%^&*()-_+=";
and
for(var i = 0; i < symbols; i++) {
var rnd = Math.floor((Math.random() * 15)); // this end of this line
rs += symbolSet[rnd];
}
In addition, I changed the useless if statement to (this can be applied to all of the fields)
if(!isNumber(amount) || amount === 0) {
amount = 1;
}
and added an isNumber function to check for valid input on all of the fields.
function isNumber(obj) {
return !isNaN(parseFloat(obj));
}

adding randomly generated number into array and summing them up

im currently doing an assignment where we have a certain amount of people play a game and each player have an attempt of scoring. The scores will be randomly generated from 1-3. The only problem i have is to store the randomly generated value into the array and then summing them up. This way, i can produce a leader board that say something like "congrats (player name) your total score is (total score)). Any suggestion on how to do these's would be great or better yet, any other alternatives would be appreciated as well. So far i've been using a incremental counter to generate the total score but it keeps generating the same number over and over again e.g. (2,2,2,2...) (1,1,1,1,....)
<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;
number = randomnumber();
for (n = 0 ; n < 11 ; ++n)
{
if (number == 0)
{
score = score + 0;
}
else if (number == 2)
{
score =score + 2;
}
else 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>
This may help, although you should try first before posting for solutions.
Create an empty array:
var myArray = [];
Add values to array (from your randomnumber() generator):
myArray.push(randomnumber());
myArray.push(randomnumber());
myArray.push(randomnumber());
Function to sum the values of some array (this is perhaps the most primitive but faster/efficient way to do it):
var sumElements = function(someArray) {
if (someArray == null) return false;
var sum = 0;
for (var i = 0, len = someArray.length; i < len; i++) {
sum += someArray[i];
}
return sum;
}
Call sumElements to find the sum:
sumElements(myArray);
Here is the simplest way to do what you need
var randomArray = [];
var randomSum = 0;
randomArray.push(randomnumber());
randomArray.push(randomnumber());
randomArray.push(randomnumber());
for(var i=0; i<randomArray.lenth; i++){
randomSum += randomArray[i];
}

Javascript - Trying count a sum from 1 to the number that user entered

I am very new to javascript, and have limited knowledge. I have just grasped the concept of hello world. At the moment, my code adds FirstNumber and SecondNumber together to give the result. I would like it to do the following:
I am trying to make a program where FirstNumber is pre-defined as 1 and SecondNumber is done by user input. The javascript should count a sum from 1 to the number that should be entered. For example, if the user entered 5, the program should count the sum from 1 to 5 (1 + 2 + 3 + 4 + 5) which will be 15. I was told to maybe use an array, although I'm not sure.
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Sum of numbers</title>
<script type="text/javascript">
function sum()
{
var FirstNumber = 1;
var SecondNumber = document.getElementById('txtSecondNumber').value;
alert(parseInt(FirstNumber) + parseInt(SecondNumber));
}
</script>
</head>
<body>
Please enter a number:<input id="txtSecondNumber" type="text" />
<input id="btnAdd" type="button" value="Add" onclick="sum();"/>
</body>
</html>
Could someone help?
Thanks :)
What you're looking for is a for loop
for (var i = FirstNumber ;i < SecondNumber ; i++){
// do what ever you want in here
// like adding i to the total
}
For the simple case of adding sequential number you dont need to loop at all:
1+2+3+4+5+...+n = n(n+1)/2
Formula from: http://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF
function sum() {
var num = document.getElementById('txtSecondNumber').value;
var sum = (num*(num+1))/2;
alert(sum);
}
While an array might help you with what you want, the important bit you're looking for is a for loop. You don't indicate your programming background or if JavaScript is your first language, but a for loop is a basic programming construct that has a starting condition, an ending condition, a way to change things (so something changes between start and end), and something to do while you're counting.
A simple for loop in JavaScript looks like this:
for( var i=0; i<10; i++ ){
alert( i );
}
This will pop-up an alert for each number from 0 to 9 inclusive.
In your case, you want to set your start condition to the first number, the end condition to check if you've done the last number (both of these can be variables - not just the constants as I've illustrated), and increment the number. Inside the loop, you'll want to be adding the number to a reference counter.
Try this, you want to loop through all the numbers in between the first and second number and add them to the result
var submit = document.getElementById('submit');
var input = document.getElementById('txtSecondNumber');
function sum() {
var FirstNumber = 1;
var SecondNumber = input.value;
var result = 0;
for (var i = FirstNumber; i <= SecondNumber; i++) {
result += i;
}
alert(result);
}
submit.addEventListener('click', sum);
jsFiddle - http://jsfiddle.net/et8t3bgd/
You can easily count a sum from 1 to any number with a for loop. If you will ever only sum up from 1, you do not need the FirstNumber variable. Otherwise, you can change i = 1 to i = FirstNumber.
var sum;
for (i = 1; i < SecondNumber+1; i++) {
sum += i;
}
function sum()
{
var SecondNumber = parseInt(document.getElementById('txtSecondNumber').value);
var result=(SecondNumber *(SecondNumber +1))/2;
alert(result);
}
Formula for sum to 1 to n number is n*(n+1)/2
As per Your Code
<!DOCTYPE html>
<html>
<head>
<title>Sum of numbers</title>
<script type="text/javascript">
function sum()
{
var SecondNumber = parseInt(document.getElementById('txtSecondNumber').value);
var result=(secondnumber*(secondnumber+1))/2;
alert(result);
}
</script>
</head>
<body>
Please enter a number:<input id="txtSecondNumber" type="text" />
<input id="btnAdd" type="button" value="Add" onclick="sum();"/>
</body>
</html>
DEMO
Here
function sum(n) {
var res = 0, total = 0;
while ((n--)>0) total += ++res;
return total;
}
Use a recursive program...
var num=Number(prompt("Enter a number"));
var sum=0;
for(var i=num;i!=0;i--){
sum+=i;
}
console.log(sum)
//print sum

Categories