Simple question, the variable total is not being displayed in the html page, could you please tell me why this is not working? I am quite new to coding.
var addtime = [0,2];
function totaltime(){
var total = 0;
for(var i in addtime) {
total += addtime[i];
}
document.getElementById("totalTime").innerHTML = total;
}
html
<h1>Total Time: <span id="totalTime"></span></h1>
You are missing call the function totaltime();
var addtime = [0,2];
function totaltime(){
var total = 0;
for(var i in addtime) {
total += addtime[i];
}
document.getElementById("totalTime").innerHTML = total;
}
totaltime();
<h1>Total Time: <span id="totalTime"></span></h1>
You didn't call the function
var addtime = [0,2];
function totaltime(){
var total = 0;
for(var i in addtime) {
total += addtime[i];
}
document.getElementById("totalTime").innerHTML = total;
}
totaltime()
<h1>Total Time: <span id="totalTime"></span></h1>
Related
I am trying to make a basic Average Calculator in HTML and JavaScript. I have the input field and buttons in HTML and the averaging and Reset functions in JavaScript. I cannot find where my problem is.
HTML Code:
<section class="script">
<script src="avg.js"></script>
<input type="number" id="inputVal" placeholder="Input Value..."></number><br>
<button id="Btn_Avg" onclick="AddFunc(inputVal.Value)">Average</button>
<button id="Btn_Rst" onclick="ResetFunc()">Reset</button>
<p>Average: </p><p id="average">OK</p>
</section>
JavaScript script (avg.js):
global var count = 0;
global var total = 0;
global var avg = 0;
global var result = document.getElementById("average");
result.textContent = 0;
function AddFunc(value){
total += value;
count += 1;
avg = total / count;
result.innerHTML = '' + avg;
}
function ResetFunc() {
total = 0;
count = 0;
avg = 0;
result.innerHTML = '0';
}
Well, for one, it should be inputVal.value (lowercase value). That should correctly pass the input value to your function. But your question doesn't really describe what issue you're running into, so I'm not sure that answers your question.
Also I don't think global is a valid keyword for JavaScript.
The problem is in this part onclick="AddFunc(inputVal.Value)". This will not pass value of inputVal to the function. You should store the <input> element in a variable and access its value using small vi.e value
var count = 0;
var total = 0;
var avg = 0;
var result = document.getElementById("average");
var input = document.getElementById('inputVal')
result.textContent = 0;
function AddFunc(e){
let value = Number(input.value);
total += value;
count += 1;
avg = total / count;
result.innerHTML = '' + avg;
}
function ResetFunc() {
total = 0;
count = 0;
avg = 0;
result.innerHTML = '0';
}
<input type="number" id="inputVal" placeholder="Input Value..."></number><br>
<button id="Btn_Avg" onclick="AddFunc(event)">Average</button>
<button id="Btn_Rst" onclick="ResetFunc()">Reset</button>
<p>Average: </p><p id="average">OK</p>
I have the following applied as a library to a CRM 2013 form
function calcServicePriceTotal() {
alert("Start");//----------HERE
if (document.getElementById("Services")) {
alert("InsideIf"); //----------HERE
var grid = document.getElementById("Services").control;
alert("ThisFar?");//----------HERE
var ids = grid.Control.get_allRecordIds()
alert("ThisFar2?");//----------HERE
for (i = 0; i < ids.length; i++) {
alert("InsideFor");//----------HERE
var cellValue = grid.control.getCellValue('iss_salesprice', ids[i]);
var number = Number(cellValue.replace(/[^0-9\.]+/g, ""));
sum = sum + number;
}
Xrm.Page.data.entity.attributes.get("ava_tempgrossvalue").setValue(sum);
alert("Done");//----------HERE
}
else {
alert("Else");//----------HERE
setTimeout("calcServicePriceTotal();", 2500);
}
}
For some reason I get as far as the alert("ThisFar?") line but then nothing else happens.
Does that mean that there is a problem with var ids = grid.Control.get_allRecordIds()? I don't know why I'm not at least seeing "ThisFar2".
Can anyone see anything obvious?
function calcServicePriceTotal() {
if (document.getElementById("Services")) {
var grid = document.getElementById("Services").control;
var ids = grid.get_allRecordIds()
var sum = 0
for (i = 0; i < ids.length; i++) {
var cellValue = grid.getCellValue('iss_salesprice', ids[i]);
var number = Number(cellValue.replace(/\D/g, ''));
number = number/100;
sum = sum + number;
}
Xrm.Page.data.entity.attributes.get("iss_value").setValue(sum);
}
else {
setTimeout("calcServicePriceTotal();", 1500);
}
}
Final working solution
Here what I have so I have a long list of check-boxes and I want to display them in text if they are check I was thinking of using the code below, but the problem I'm having is if they check and uncheck a check-box it shows up multiple times any suggestion on how to fix this?
.innerHTML += id;
If you need some more details here's a code dump of the relevant code:
Javascript
function findTotal() {
var items = new Array();
var itemCount = document.getElementsByClassName("items");
var total = 0;
var id = '';
for (var i = 0; i < itemCount.length; i++) {
id = "c" + (i + 1);
if (document.getElementById(id).checked) {
total = total + parseInt(document.getElementById(id).value);
document.getElementById(id).parentNode.classList.add("active");
document.getElementById(id).parentNode.classList.remove("hover");
document.getElementById('display').innerHTML += id;
} else {
document.getElementById(id).parentNode.classList.remove("active");
document.getElementById(id).parentNode.classList.add("hover");
}
}
console.log(total);
document.getElementById('displayTotal').value = total;
}
HTML
<label class="hover topping" for="c4">
<input class="items" onclick="findTotal()" type="checkbox" name="topping" value="1.00" id="c4">BABYBEL</label>
Note: many more label classes
Previous answer should do it. Here your code (see comment "clear container"
Additionally I have simplified your code a bit. Readability greatly increased.
Maybe you should switch to jQuery in general, much simpler for your example.
var displayElement = document.getElementById('display'),
displayTotalElement = document.getElementById('displayTotal');
function findTotal() {
var items = [],
itemCount = document.getElementsByClassName("items"),
total = 0,
id = '';
// clear container
displayElement.innerHTML = "";
for (var i = 0; i < itemCount.length; i++) {
id = "c" + (i + 1);
var element = document.getElementById(id),
elementsParent = element.parentNode;
if (element.checked) {
total = total + parseInt(element.value, 10);
elementsParent.classList.add("active");
elementsParent.classList.remove("hover");
displayElement.innerHTML += id;
} else {
elementsParent.classList.remove("active");
elementsParent.classList.add("hover");
}
}
console.log(total);
displayTotalElement.value = total;
}
Reset the text before the loop:
document.getElementById('display').innerHTML = '';
At the moment you're just always adding to whatever's already thereā¦
when I call this function "showMe(calcTotal(myNumberArray));" in the console it works, but it doesn't work when called in the code. Sorry if my code herts you eyes or doesn't make since. it's supposed to calculate the total. I would like to know why the browser doesn't see the invocation or why the value is not displayed on the screen.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
</style>
</head>
<body>
<button id="hit">hit</button>
<div id="number"></div>
<div id="arrayOutput"></div>
<div id="someId"></div>
<div id="out2"></div>
<script>
//Services helper functon
var myNumberArray = [];
document.getElementById('hit').onclick = function randomNumber() {
var card = Math.floor(Math.random() * 10) + 1;
document.getElementById('number').innerHTML=card;
myNumberArray.push(card);
var number =myNumberArray.value;
var arrayOutput = document.getElementById('number');
var someId = document.getElementById('someId');
someId.innerHTML = myNumberArray;
};
//var output = myNumberArray = calcTotal(list);
function calcTotal(myNumberArray) {
var total = 0;
for(var i = 0; i < myNumberArray.length; i++){
total += myNumberArray[i];
}
return total;
}
//document.getElementById('out2').innerHTML = out2;
what = calcTotal(myNumberArray);
var what= calcTotal(myNumberArray);
function showMe(VAL) {
var parent = document.getElementById('out2');
parent.innerHTML = VAL;
}
showMe(calcTotal(myNumberArray));
</script>
</body>
</html>
If you want to update the total value on click of the button, then you need to call showMe(calcTotal(myNumberArray)); inside the click handler.
//Services helper functon
var myNumberArray = [];
document.getElementById('hit').onclick = function randomNumber() {
var card = Math.floor(Math.random() * 10) + 1;
document.getElementById('number').innerHTML = card;
myNumberArray.push(card);
var number = myNumberArray.value;
var arrayOutput = document.getElementById('number');
var someId = document.getElementById('someId');
someId.innerHTML = myNumberArray;
showMe(calcTotal(myNumberArray));
};
//var output = myNumberArray = calcTotal(list);
function calcTotal(myNumberArray) {
var total = 0;
for (var i = 0; i < myNumberArray.length; i++) {
total += myNumberArray[i];
}
return total;
}
//document.getElementById('out2').innerHTML = out2;
what = calcTotal(myNumberArray);
var what = calcTotal(myNumberArray);
function showMe(VAL) {
var parent = document.getElementById('out2');
parent.innerHTML = VAL;
}
showMe(calcTotal(myNumberArray));
<button id="hit">hit</button>
<div id="number"></div>
<div id="arrayOutput"></div>
<div id="someId"></div>
<div id="out2"></div>
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