I am attempting to write a script that will allow users to input numbers into a screen, add them to an array and then print the values on an innerHTML element.
However, when I attempt to use it in a for loop, nothing is printing out and it goes to a new page where the only thing displayed is the first number entered.
I am new at JavaScript and might be doing it incorrectly. Please let me know!
Thanks in advance
var a = [];
var count = 0;
function addNum() {
a[count] = document.getElementById('input').value;
count++;
}
function printValues() {
for (i = 0; i < a.length; i++) {
document.write(a[i], " ").innerHTML = array;
}
}
<input type="text" id="input">
<br>
<input type="button" onclick="addNum();" value="Add Number">
<br>
<input type="button" onclick="printValues();" value="Print Numbers">
<p>
<a id="array"></a>
</p>
From MDN:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.
So your problem is caused by document.write. Once you write to your already loaded document, everything else is thrown away, including your javascript. (You had other problems too with just how you were using it, but this is the main problem).
You have an element with the id array, which I assume is where you want to put your numbers. So you need to get that element with getElementById and then set its innerHTML. You can use array.join to avoid the loop.
var a = [];
var count = 0;
function addNum() {
a[count] = document.getElementById('input').value;
count++;
}
function printValues() {
document.getElementById('array').innerHTML = a.join(",");
}
<input type="text" id="input">
<br>
<input type="button" onclick="addNum();" value="Add Number">
<br>
<input type="button" onclick="printValues();" value="Print Numbers">
<p>
<a id="array"></a>
</p>
A couple of other things you should look at. After adding a number in addNum, you should probably clear the text box by setting the value to null. Secondly, it's preferred to add event handlers in code rather than in your HTML.
function printValues() {
var strValues=''; // Initialize a temporary variable
for (i = 0; i < a.length; i++) {
strValues += a[i] + ' ';
}
document.write(strValues); //Writting variable to document.
}
In the above example we have create a temporary variable and sets the default value to blank. Then in for loop we concatenate the array value to variable using += sign.
What you are doing is not the correct way of setting stuff up in innerHTML . Also, you are not retaining the values to be printed on to the screen. Everytime , you click on print the new value inputted by the user is just getting passed and the old value is getting replaced with the new one . Here the variable valueToBePrinted will always remember the last value that was inputted as it concatenates all the inputted values to it, once the user is done with his/her input .
Look at the following piece of code :
var a = [];
var count = 0;
function addNum() {
a[count] = document.getElementById('input').value;
console.log(a[count]);
count++;
}
function printValues() {
var valueToBePrinted='';
for (i=0;i<a.length;i++) {
valueToBePrinted += a[i] + ' ';
console.log(valueToBePrinted)
document.getElementById('array').innerHTML =valueToBePrinted;
}
}
Also , look at the result in the Fiddle here : Fiddle
The statement "document.write(a[i], " ").innerHTML = array;" is wrong.
There is no variable named array declared in the code.
The correct form to print all the numbers using document.write is,
for (i=0;i<a.length;i++) {
document.write(a[i] + " ");
}
If you need sum of all input numbers and the print the sum, then you can simply sum it up in a variable as you click addNumber button as,
var total = 0;
function addNum() {
total += Number(document.getElementById('input').value);
}
function printValues() {
document.write(total);
}
You typically would not use a "count" variable to add items to an array but would instead push to the array however I kept it in case you needed it otherwise.
You would as others noted not do a document.write to an element but instead use the innerHTML and replace or append to that.
Odd also that you are putting the innerHTML in a link <a /> element but since that is what you are using I will reproduce that.
IF you do want to use these as number (integers?) you would want to parse them with parseInt(string, radix); or parsefloat.
You did not have i set as a variable object so I did that here
Slightly reworked code here:
var a = [];
var count = 0;
function addNum() {
a.push(parseInt(document.getElementById('input').value, 10));
count++;
}
function printValues() {
var i;
var myValues = "";
for (i = 0; i < a.length; i++) {
myValues = myValues + a[i] + " ";
}
var element = document.getElementById("array");
element.innerHTML = myValues;
}
Here is the code reproduced as a working example: http://jsfiddle.net/coffw8tg/
Related
so I wrote a script to display 5 random arrays, but the page doesn't display anything.
here's the code:
<html>
<head>
<script>
function start(){
var arr(5),result;
result=document.getElementById("arraying");
result="<p>";
for(var i=0; i<5;i++){
arr[i]=Math.floor(Math.random()*10);
result+="arr["+i+"]= "+arr[i]+"</p><p>";
}
result+="</p>";
}
window.addEventListener("load",start,false);
</script>
</head>
<body>
<div id="arraying"></div>
</body>
</html>
I tried removing result=document.getElementById and write document.getElementById.innerHTML=result in the end of the function but didn't work. what's the error?
You cannot use the same variable for different purposes at the same time. First you assign a DOM element to result, and immediately on the next line you overwrite result with a string.
Build a string htmlStr inside your loop, and when that is done, assign this string to result.innerHTML property:
function start() {
let arr = [],
result, htmlStr = '';
result = document.getElementById("arraying");
htmlStr += "<p>";
for (let i = 0; i < 5; i++) {
arr[i] = Math.floor(Math.random() * 10);
htmlStr += "arr[" + i + "]= " + arr[i] + "</p><p>";
}
htmlStr += "</p>";
result.innerHTML = htmlStr;
}
window.addEventListener("load", start, false);
<div id="arraying"></div>
Looking at the code you seem to be missing some basic javascript concepts.
array size
This is probably your main issue:
var arr(5)
This does not make sense in javascript. Array length does not need to be predefined since all arrays are of dynamic length. Simply define an array like this:
var arr = []
Then later when you want to append new elements use push like this:
arr.push( Math.floor(Math.random()*10) )
adding html using innerHTML
There are different ways to dynamically inject html into your page. (It looks like) you tried to append the html as a string to the parent element. This is not possible.
You said you tried using innerHTML. That should work if used correctly.
A working implementation would work like this:
function start() {
var arr = []
var result = "<p>"
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) ) // Btw this array isn't actually needed.
result += "arr[" + i + "] = " + arr[i] + "</p><p>"
}
document.getElementById("arraying").innerHTML = result
}
window.addEventListener("load", start, {passive: true});
adding html using createElement
A generally better way of dynamically adding html elements is via createElement.
This way you dont have to write html and are therefore less prone for making errors. It is also more performant and easier to integrate into javascript.
I think the best explaination is a commented implementation:
function start() {
var myDiv = document.getElementById("arraying") // get parent node
var arr = []
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) )
var p = document.createElement("p") // create p element
p.innerText = "arr[" + i + "] = " + arr[i] // add text content to p element
myDiv.append(p) // append p element to parent element
}
}
window.addEventListener("load", start, {passive: true});
small tips
The let keyword works mostly the same as the var keyword, but is generally preferred because of some edge cases in which let is superior.
Fusing strings and variables using the plus operator is generally considered bad practice. A better way to do the string concatenation would have been
result += `arr[${i}] = ${arr[i]}</p><p>`
I am trying to make a web tool that takes user imputed values as a list of objects and a number of objects to randomly choose and then will print out the number of objects chosen from the list at random when the button is clicked. However i have not been able to get anything to print. I have tried to call the variables both with qoutes and without them and i still haven't gotten the compute to print any results in the final read only textbox. I think the issue is somewhere in my script functions but i cant figure out where and i've spent hours looking up syntax and possible issues to no avail. Ive tried to work with inner.html without success and the current method (document.getById....) is copied from http://www.mauvecloud.net/randomchooser.html that works to randomly choose one thing and print the result.
<html>
<style></style>
<head>
<title>Random Chooser</title>
<script>
Array.protoype.chooseFromArray() = function(){
var chosenIndex = Math.floor(Math.random() * ValueArray.length);
var elementPicked = ValueArray["chosenIndex"];
ValueArray.splice("chosenIndex",1);
return elementPicked;
}
function chooseRandomly(){
var ValueArray = document.getElementById("valuelist").value.split("\n");
var numItems = document.getElementById("items").value;
var ReturnArray = [];
for(i=0; i < numItems; i++){
var element = ValueArray.chooseFromArray();
ReturnArray.push("element");
}
document.getElementById("result").value = ReturnArray.toString();
}
</script>
<body>
Enter some values, one on each line, then click the choose button to pick randomly.
<form action onsubmit="return false;">
<textarea id="valuelist" rows="15" cols="60"></textarea>
<br>
<br>
Randomly choose <input type="number" id="items" > items
<br>
<input type="button" value="Choose" onclick="chooseRandomly();return false">
<br>
<br>
<input id="result" type="text" size="80" value readonly="readonly">
<br>
<br>
</form>
</body>
</html>
You're confused on a few JavaScript syntax points. I won't bother correcting the non-idiomatic style, you should read more about that here on your own once you understand the changes outlined below.
First, here's the cleaned up and fixed version so we can take a look at it together:
Array.prototype.chooseFromArray = function() {
var chosenIndex = Math.floor(Math.random() * this.length);
var elementPicked = this[chosenIndex];
this.splice(chosenIndex, 1);
return elementPicked;
}
function chooseRandomly() {
var ValueArray = document.getElementById("valuelist").value.split("\n");
var numItems = document.getElementById("items").value;
var ReturnArray = [];
for (var i = 0; i < numItems; i++) {
var element = ValueArray.chooseFromArray();
ReturnArray.push(element);
}
document.getElementById("result").value = ReturnArray.toString();
}
window.chooseRandomly = chooseRandomly;
First thing's first, to reference a function from HTML on JSFiddle you'll need it to be defined on the window. You don't normally need to do that, so you can mostly ignore that point.
Generally, you have several syntax errors.
Defining a property on an object (prototypes are objects (MDN)) happens just like variable assignment, so you just write object.<property_name> = value. You were calling chooseFromArray then assigning to that call (which is just invalid syntax).
When creating functions for prototypes, this will usually reference the object calling the function. In this case, any array calling chooseFromArray will have itself bound to the this reference inside the prototype function.
When accessing properties through the indexer you just pass the string. If it's a variable, you don't surround it with strings. Ex:
var chosenIndex = 123;
var elementPicked = this["chosenIndex"];
// This is the same as this.elementPicked;
var elementPicked = this[chosenIndex];
// This is what you want as you're accessing the `123` property on `this`
The same goes for passing variables to functions. You just pass the variable. Anything inside of 's, ' ` 's and "s are string literals and will not reference any variables.
I am new to Javascript and am just playing around trying to print a simple for loop to the HTML.
HTML:
<div id="hello"</div>
JS :
var text="";
for (var i=0;i<10;i++) {
document.getElementById("hello").innerHTML=text+i;
}
My problem is that this code only outputs the last iteration '9', and not '0123456789' which is what I want.
Now if i do document.write it prints out the numbers fine but I heard this is bad practice so I just want to do it the correct way.
Thanks
It would be better to build your text content first and insert it into HTML element once (to save some time):
var text="";
for (var i=0;i<10;i++) {
text += i;
}
document.getElementById("hello").innerHTML = text;
You should use the addition assignment operator += that adds a value to a variable, so you're just missing + before = in :
document.getElementById("hello").innerHTML += text+i;
NOTE : Use textContent instead of innerHTML because you're appending just a text, check example bellow.
var text="";
for (var i=0;i<10;i++) {
document.getElementById("hello").textContent += text+i;
}
<div id="hello"></div>
I have indexed a bunch of inputs in my html form.
I want to loop through the inputs and create an array. From that array I want to collect the total (sum) of the fields and finally append another HTML input to display that total.
I know how to do this in PHP but I am struggling with JavaScript and I need it done client side.
I have tried to construct as much of this as possible. Here is a jsFiddle:
Here is my html:
<div style="padding:5px;clear:both;"><input type="text" name="total_inkind" id="total_inkind" placeholder="$" onchange="calcInKind()"></div>
and Javascript:
function calcInKind() {
var runningTotal = 0;
var i = 0;
for (var i = 0; document.getElementById('inkind').value; i++){
if(document.getElementById('inkind').value != ''){
$gwyl_gr = document.getElementById('inkind').value;
$runningTotal = parseFloat($runningTotal) + parseFloat($gwyl_gr);
}else{
$gwyl_gr = 0;
}
i = i++;
}
document.getElementById('total_inkind').value = $runningTotal;
}
For something as simple as a sum of all the form elements, you don't really need an array unless you want to manipulate every value in more ways than one. You can however loop over every input you had in the form, taking its value and adding it to the total.
Looking at your code however, I have to remark that Javascript does not require variables to be preceded by a $ unlike PHP. You however have the opportunity to use them, which JQuery users often do, to denote that their variable is in fact a JQuery variable.
I forked your JSFiddle and rewrote some things to get it working as the question states: JSFiddle
function sumTheInkinds() {
var runningTotal = 0;
var ourlist = document.getElementsByClassName("inkind");
for (var i = 0; i < ourlist.length; i++) {
if (ourlist[i].value != '') {
try {
runningTotal = runningTotal + parseFloat(ourlist[i].value);
} catch (err) {
alert ("Value was not a float!");
}
}
}
document.getElementById('total_inkind').value = runningTotal;
};
document.getElementById("runcalc").onclick = sumTheInkinds;
My implementation however relies on a button press which may not be intended, which can easily be changed back to onchange by applying this:
var inks = document.getElementsByTagName("inkind");
for (var i=0;i<inks.length;i++) {
inks.onchange = sumTheInkinds;
}
I'm trying to change the value of an input field with Javascript.
I tried everything, but nothing seems to works. I tried putting the 5 between quotation marks and using jquery. I also double-checked the array and everything.
Here is the input code:
<input type="number" id="id_[SOME_ID_HERE]" value="0">
and the loop used to update the values.
for (var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
document.getElementById("id_" + val.substring(3)).value = 5;
}
jsfiddle: http://jsfiddle.net/zkTud/
EDIT: Seems like it doesn't work with type="text" as well...
EDIT2: Thank you everyone who answered. My problem was actually something else.
The input was loaded from another page, and it took time and the for loop I had problem with (see above) was executed before the file was done loading.
All I did was to move the for loop as is to the callback function and it works now.
Thanks anyways!
I really appreciate the help I'm getting in this site! :)
The problem is that your call to substring is returning too much of the string, so there are no elements found by getElementById. Change it to this:
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
document.getElementById("id_" + val.substring(5)).value = 5;
}
Here's an updated fiddle.
The substring method (when called with one argument) returns the characters from the index specified to the end of the string. Since you are specifying index 3, you get "d_1", "d_2" etc. when actually you just want the number.
Alternatively, you could of course change the string to which you append the substring, but I think that would be more confusing to read (not immediately obvious which element will be returned):
document.getElementById("i" + val.substring(3)).value = 5;
demo http://jsfiddle.net/bY4EV/6/
sustring(3) gives d_1 : How to substring in jquery
hope this helps
code
var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
$("#id_" + val.substring(5)).val("5");
}
Check this, JSFiddle , Updated and corrected your problem.
Code:
var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
$("#id" + val.substring(4)).val( "5");
}