I have a site where I can enter the amount of an item, it will then take that input value and return the result on the page. I am then trying to get the results of all the items and return a grand total.
The issue is when I a loop to do this it will only add the first one.
I created a fiddle: https://jsfiddle.net/rc1mgLj5/4/
I am using querySelectorAll and using the length of all the classNames for the result of the first return.
Then looping them after parsing them to a number from text.
But at the moment it is only doing the first calculation. If I delete the for loop the first part works correctly again.
So since its only doing the first calculation for the first item, I get NaN for the second because it does not have a number to parse.
const total = document.querySelectorAll(".tot");
const price = document.querySelectorAll(".cost");
let textval = document.querySelectorAll(".qty-item");
const cal = document.getElementById("calc");
const errorMessage = document.querySelectorAll(".error");
cal.addEventListener("mouseover", function(e) {
console.log(total);
for (var i = 0; i < price.length; i++) {
let xPrice = price[i].innerHTML.split("$");
let parsePrice = parseFloat(xPrice[1]);
if (textval[i].value === "" || isNaN(textval[i].value)) {
setMessage("Please enter a number", "red");
} else {
let x = parseFloat(textval[i].value);
let y = parsePrice;
let z = x * y;
total[i].innerText = z.toFixed(2);
total[i].innerText = z;
for (i = 0; i < total.length; i++) {
let j = parseFloat(total[i].innerHTML);
console.log(j);
}
}
}
});
HTML:
<body>
<div class="main">
<span class="title">A Title</span>
</div>
<div class="content">
<div class="item">
<span>Item 1</span>
</div>
<div>
<span class="cost">$100.00</span>
</div>
<div id="qty">
<label>QTY:</label><input placeholder="0" class="qty-item">
<p class="error"></p>
</div>
<div class="tot">
<span><label>TOTAL</label> $0.0</span>
</div>
</div>
<br><br>
<div class="main">
<span class="title">A Title</span>
</div>
<div class="content">
<div class="item">
<span>Item 2</span>
</div>
<div>
<span class="cost">$50.00</span>
</div>
<div class="qty">
<label>QTY:</label><input placeholder="0" class="qty-item">
<p class="error"></p>
</div>
<div class="tot">
<span><label>TOTAL</label> $0.0</span>
</div>
</div>
<div class="calc-button">
<button id="calc">Calculate Prices</button>
</div>
</body>
You are nesting two fors using the same i variable as index:
cal.addEventListener('mouseover', function(e) {
console.log('total', total);
for (var i = 0; i < price.length; i++) {
//...
for (i = 0; i < total.length; i++) { // <== uses "i" again
let j = parseFloat(total[ii].innerHTML);
console.log(j);
}
}
}
});
Just replace that second for's variable with another name. Example:
for (let k = 0; k < total.length; k++) {
let j = parseFloat(total[k].innerHTML);
console.log(j);
}
Demo: https://jsfiddle.net/acdcjunior/gpLvszx3/
It seems you are using the same variable "i" for both loops and i is being reset in the second loop to 3 and hence the main loop runs only once. So i removed the following code and calculated the total outside main loop. seems to be working fine now. https://jsfiddle.net/uxr7ac9k/7/
total[i].innerText = z;
for (i=0;i < total.length; i++){
let j = parseFloat(total[i].innerHTML);
console.log(j);
}
okay here is the question -- .. i tried it but my js isn't working and idk where i am wrong here is the question
THE PROBLEM IS AFTER THE JS EXECUTED IT DOESN'T RUN ... LIKE IDK WHERE THE PROBLEM IS ; I KNOW IT LOADS BUT IT DOES'NT WORK
<html>
<head>
<script src="q2.js" type="text/javascript"> </script>
</head>
<div > Input 1 <input type="text" id ="input1"></div>
<div> Input 2 <input type="text" id ="input2"> </div>
<div> Result <div id="result"> </div></div>
<button onclick= "compute()">Compute</button>
</body>
</html>
the js is here
function compute(){
var n = (document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var i,j;
if (Number(n)){
}
else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)){
}
else {
alert("Error! Please put a valid Number - on input 2 ");
}
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
result.innerHTML += "X";
if(j == (m-1)){
result.innerHTML += "<br />";
}
}
}
}
result.innerHTML += "X";
You forgot to set the variable result:
var result = document.getElementById("result");
And there is a loneley ( in var n = (document.getElementById("input1").value; wich will through syntax error
And you might want to clear the content of your "result"-container when calling the function again: result.innerHMLT = ''
function compute() {
var n = document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var result = document.getElementById("result");
result.innerHMLT = ''
var i, j;
if (Number(n)) {} else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)) {} else {
alert("Error! Please put a valid Number - on input 2 ");
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
result.innerHTML += "X";
if (j == (m - 1)) {
result.innerHTML += "<br />";
}
}
}
}
<div>Input 1
<input type="text" id="input1">
</div>
<div>Input 2
<input type="text" id="input2">
</div>
<div>Result
<div id="result"></div>
</div>
<button onclick="compute()">Compute</button>
I want to input the amount of array and the output will follow as it's amount.
Ex: If I put "7" in the input text. the result will show as much as 7.
Here's my code:
<html>
<head>
<title>JavaScript - Input Text Field</title>
</head>
<body>
<form name="test">
<H2>Enter something into the field and press the button. <br></H2>
<P>Amount of Tables: <input type="TEXT" name="amount"><BR><BR>
<input type="Button" Value="Show and Clear Input" onClick="myFunction()"></P>
</form>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount");
for (i = 0; i < j.length; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
You have something wrong on your JavaScript
See code:
function myFunction() {
var text = "";
var i;
var j = document.getElementsByName("amount")[0];
for (i = 0; i < j.value; i++) {
text += "The number is " + j.value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
.getElementsByName returns an array of elements, so you need to specify the index of your element so that you can access its properties.
Fiddle here
I have tried to generate rnadom number(1-9) in 9 div's. How to avoid number repitations? But it's not working, why i cant get output? Thanks in advance.
Here is my code:
<html>
<head>
<title>Random_No</title>
<link rel="stylesheet" type="text/css" href="rno.css">
<script src="rno.js" ></script>
</head>
<body class="outer" onload=random()>
<div id="input1" ></div>
<div id="input2" ></div>
<div id="input3" ></div>
<div id="input4" ></div>
<div id="input5" ></div>
<div id="input6" ></div>
<div id="input7" ></div>
<div id="input8" ></div>
<div id="input9" ></div>
<script>
function random()
{
var a=new Array("input1","input2","input3","input4","input5","input6","input7","input8","input9");
x=a.length;
var ran=new Array();
for(var i=0;i<x;i++)
{
ran[i]=Math.floor(Math.random()*9);
}
for(var i=0 ; i<x ; i++)
{
document.getElementById("a[i]").innerHTML=ran[i];
}
}
</script>
</body>
</html>
Replace
document.getElementById("a[i]").innerHTML=ran[i];
By
document.getElementById(a[i]).innerHTML=ran[i];
And... why 2 loops ?
Because you only want a small set of items randomised with no repeats and to take each one, a Fisher-Yates shuffle would be very efficient here.
var inputs = [], i;
for (i = 1; i < 10; ++i) // get each input
inputs.push(document.getElementById('input' + i));
function shuffleArray(a) { // Fisher-Yates shuffle, no side effects
var i = a.length, t, j;
a = a.slice();
while (--i) t = a[i], a[i] = a[j = ~~(Math.random() * (i+1))], a[j] = t;
return a;
}
inputs = shuffleArray(inputs); // shuffle
for (i = 0; i < 9; ++i) // give values (already shuffled)
inputs[i] = i + 1; // there will be no repeats because we're counting up
Another way to generate randoms from a set-
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Random_No</title>
</head>
<body >
<div id= "input1"></div>
<div id= "input2"></div>
<div id= "input3"></div>
<div id= "input4"></div>
<div id= "input5"></div>
<div id= "input6"></div>
<div id= "input7"></div>
<div id= "input8"></div>
<div id= "input9"></div>
<script>
function random_no(){
var i=0, ran=[1,2,3,4,5,6,7,8,9];
while(i<9){
document.getElementById("input"+(++i)).innerHTML=
ran.splice(Math.floor(Math.random()*ran.length),1);
}
}
onload=random_no;
</script>
</body>
</html>
You need to change
document.getElementById("a[i]").innerHTML = ran[i];
to
document.getElementById(a[i]).innerHTML = ran[i];
because putting quotes around a[i] makes it look for an element whose id is actually "a[i]"
You can map the elements in another array, shuffle it and inject the random number in basically one chained operation using some array methods:
var divs = document.getElementsByTagName('div');
[].map.call(divs, function(e, i) {
return i;
}).sort(function() {
return (Math.round(Math.random())-0.5);
}).forEach(function(r, i) {
divs[i].innerHTML = r;
});
DEMO: http://jsfiddle.net/EsGL3/
You can use Array.sort() with a random comparator to re-order the values:
JSFIDDLE
function random()
{
var x = 9,
ids = [ 'input1', 'input2', 'input3',
'input4', 'input5', 'input6',
'input7', 'input8', 'input9'
],
values = [1,2,3,4,5,6,7,8,9],
i = 0;
Array.sort( values, function(a,b){ return Math.random() < 0.5 ? 1 : -1; });
for( ; i < x; ++i)
{
document.getElementById( ids[i] ).innerHTML = values[i];
}
}
I am trying to add a bulleted list to the page after the user enters 'exit' into a prompt; the list should not include the term 'exit'. I was able to get the list in full using document.write but this included the 'exit' and got rid of my page formatting. I am pretty sure I need to use innerHTML, but when I do this all I get is the page without any of the array items. Any help is greatly appreciated.
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script>
function askMe() {
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit'){
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
var MyList = getElementById('results');
MyList.innerHTML = "<li>"+list+"</li>";
}
}
</script>
</head>
<body onload="askMe()">
<ul>
<div id="results">
</div>
</ul>
<br/>
<br/>
</body>
you have to use document.getElementById() and also generate a string inside the loop and use inner html after the loop so that the previous li's dont get over written.
update the code portions like
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++){
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
and in html , remove the div inside ul and giv id to ul
<ul id="results">
</ul>
and here is the full code becomes:
<html>
<head>
<img src="http://profperry.com/Classes20/JavaScript/lordoftherings.png" />
<title>Javascript Test</title>
<script type="text/javascript">
function askMe()
{
var fav_characterList = new Array();
i = 0;
var fav_character = "";
while(fav_character != 'exit')
{
fav_character = prompt("Who's your favorite Lord of the Rings character\n\n Enter 'exit' to stop prompting", "");
fav_characterList[i] = fav_character;
i++;
}
n = (fav_characterList.length);
var kk="";
for(i = 0; i <= (n-1); i++)
{
var list = fav_characterList[i];
kk += "<li>"+list+"</li>"
}
var MyList = document.getElementById('results');
MyList.innerHTML = kk;
}
</script>
</head>
<body onload="askMe()">
<ul id="results">
</ul>
<br/>
<br/>
</body>
</html>
You should use MyList.innerHTML += "<li>"+list+"</li>"; (notice the use of += instead of =)
Also, change your <ul> HTML to be:
...
<ul id="results">
</ul>
...