This is a basic html/javascript code, but I am having issues getting the sum of all fields.
(The are 50 fields in the original project, but now I just leave 5)
If the field is blank, it just has to ignore it, and add only those with filled fields.
HTML code:
value1:<input type="text" id="total_1" ><br>
value2:<input type="text" id="total_2" ><br>
value3:<input type="text" id="total_3" ><br>
value4:<input type="text" id="total_4" ><br>
value5:<input type="text" id="total_5" ><br>
total:<input type="text" id="totalresult" >
<button type="button" onclick="getTotal(); return false;">Get total</button>
Javascript:
function getTotal() {
var sum;
for (i = 1; i <=5 ; i++) {
var total = document.getElementById('total_' + i.toString()).value;
if (total != '') {
sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
}
I don't know why my code is isn't working.
Here is my Fiddle
The first time your code runs, sum will be undefined.
Initialize
var sum = 0;
Also to make it work in the fiddle, you need to change
the onLoad on the left top to 'No wrap - in '
You need to do two things. 1, initialize sum to zero. 2, check the input values for not being a number.
function getTotal() {
var sum = 0;
for (i = 1; i <= 5; i++) {
var total = document.getElementById('total_' + i).value;
if (!isNaN(parseFloat(total))) sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
jsFiddle example
I don't know why your fiddle can't figure out to make getTotal a global. But your main problem is that sum is undefined as start. This will result in NaN (Not a Number) :
var sum;
sum = 1 + sum; // NaN
....
sum = 1 + undefined; // NaN
sum = 1 + NaN; // NaN
Demo at jsbin.com
You should set sum equal zero at first:
var sum = 0;
for ( ... ) { ...
Working demo as adrianp pointed out: It would probably be more clear if you uploaded the working code to jsbin.
You haven't defined sum variable so javascript takes that as NaN, which means Not a Number. You need to initilaize it to set it right.
function getTotal() {
var sum = 0;
for (i = 1; i <=5 ; i++) {
var total = document.getElementById('total_' + i.toString()).value;
if(isNaN(total) || total.indexOf(' ') == 1) {
alert("Please type a number");
document.getElementById("totalresult").value = "I cant sum alphanumerics";
return false;
}
if (total != '') {
sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
}
FIDDLE
Use IsNumeric function to check if the input field has a valid number. See: Validate decimal numbers in JavaScript - IsNumeric()
Here is my suggestion to improve the code inside your for loop:
var elementValue = document.getElementById('total_' + i).value
IsNumeric(elementValue) ? elementValue : elementValue = 0;
Related
var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
var val = binaryValue.value;
var result = 0;
var i = val.length-1;
var j = 0;
while (i > -1) {
var y = (Number(val[i])) * (2 ** [j]);
result += y;
i--;
j++;
console.log(y);
}
decimalValue.value = result;
console.log(binaryValue.value);
}
Using the code above, I tried to obtain a value from an input field and do a calculation to convert it to a decimal number. But it doesn't obtain the input value. I tried several times and I am unable to figure out it.
This is how you get a value from an input field:
var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
var NumValue = binaryValue.value
console.log("input value: " + NumValue);
//this is how you convert a binary number to decimal
console.log("binary number: " + (NumValue >>> 0).toString(2));
//this is how you convert an decimal number to binary
console.log("decimal number: " + parseInt(NumValue, 2));
}
<input type="text" id="binary" placeholder="insert value"/>
<button type="button" onclick="binaryToDecimal()">Show value</button>
Use this example to fix your code.
I also added ways to convert to and from binary numbers.
I have the following function in javascript to calculate the average:
function calculaMediaFinal () {
var soma = 0;
for(var i = 1; i>5; i++) {
soma += parseInt(document.getElementById('resultado' + i).value, 10);
}
var media = soma / 5;
var inputCuboMedia = document.getElementById('ConcretizaObj');
inputCuboMedia.value = parseInt(media, 10);
}
function ContarObjetivos() {
let contador = 0;
if(document.getElementById('resultado' + i).value) {
contador++;
}
}
But I have a problem, it's that I put in that at most there are 5 which is not true, because the user is who chooses how many results he wants. That is, the 5 can not be filled if the user only wants 4. How do I average without the number 5 but with the number of results that the user wants?
You can do it like this.
create input element and let user pass each number into it separated by space
create button that will trigger the code that calculates the average
create element that will store the result
To perform the actual computation
get value of input field, split it at space ' ', remove white spaces around each separate number using trim
sum the array created in the previous step using reduce
divide the sum by the amount of provided numbers
const input = document.querySelector('input');
const btn = document.querySelector('button');
const res = document.querySelector('p > span');
function getAverage() {
const values = input.value.split(' ').map(v => v.trim());
const sum = values.reduce((acc, v) => acc + Number(v), 0);
res.textContent = (sum / values.length);
}
// 1 2 3 4 5 6 7 8 9 10
btn.addEventListener('click', getAverage);
<input type='text' />
<button>get average</button>
<p>result: <span></span></p>
Where you pass numbers into input field one by one separated by space (try passing 1 2 3 4 5 6 7 8 9 10) and then click button to perform the computation which then will be shown in span element.
Your loop wasn't executed:
In a for, the second parameter is the condition for which the iteration is going to be executed (true = execute). Changing > to <= made it work.
I also merged your two functions so that a not filled input doesn't count.
Here is a working snippet where I used all your code:
// Merged both function:
function calculaMediaFinal() {
let soma = 0;
let contador = 0;
for (var i = 1; i <= 5; i++) { // Changed > to <= here
if (document.getElementById('resultado' + i).value) {
soma += parseInt(document.getElementById('resultado' + i).value, 10);
contador++;
}
}
var media = soma / contador;
var inputCuboMedia = document.getElementById('ConcretizaObj');
inputCuboMedia.value = parseInt(media, 10);
}
<input id="resultado1"><br>
<input id="resultado2"><br>
<input id="resultado3"><br>
<input id="resultado4"><br>
<input id="resultado5"><br>
<button onclick="calculaMediaFinal();">calcula</button>
<br> Media:
<input id="ConcretizaObj">
⋅
⋅
⋅
If you don't need to specify the "base" in the parseInt function, I also suggest you to use the unary + operator:
// Merged both function:
function calculaMediaFinal() {
let soma = 0;
let contador = 0;
for (var i = 1; i <= 5; i++) { // Changed > to <= here
if (document.getElementById('resultado' + i).value) {
soma += +document.getElementById('resultado' + i).value;
contador++;
}
}
var media = soma / contador;
document.getElementById('ConcretizaObj').value = media;
}
<input id="resultado1"><br>
<input id="resultado2"><br>
<input id="resultado3"><br>
<input id="resultado4"><br>
<input id="resultado5"><br>
<button onclick="calculaMediaFinal();">calcula</button>
<br> Media:
<input id="ConcretizaObj">
Hope it helps.
If I understand your question correct, you want something like this. Create a new numeric input field that stores the amount that the user wants. Put the value of the input field in a variable and use it in your code? Also it probably needs to be '<=' in the for loop to be executed. For example
HTML add next line in your code:
<input type="number" id="userAmount" />
Javascript:
function calculaMediaFinal () {
var soma = 0;
var amount = parseInt(document.getElementById("userAmount").value);
for(var i = 1; i<=amount; i++) {
soma += parseInt(document.getElementById('resultado' + i).value, 10);
}
var media = soma / amount;
var inputCuboMedia = document.getElementById('ConcretizaObj');
inputCuboMedia.value = parseInt(media, 10);
}
function ContarObjetivos(){
let contador = 0;
if(document.getElementById('resultado' + i).value) {
contador++;
}
}
Here is the code as far as I got it right now:
<!DOCTYPE html>
<html>
<body>
<button onclick="scanarray('a', 'max')">Test with a, max</button>
<button onclick="scanarray('b', 'min')">Test with b, min</button>
<p id="demo">test</p>
<script>
var array = [{"a":1},{"b":3},{"a":6},{"b":10}];
var max = null;
var min = null;
var value = null;
function scanarray(scanval, searchterm) {
if (array.length < 1) {
return -1;
}
if(searchterm == "max"){
max = Math.max.apply(Math,array.map(function(e){return e.scanvalue;}))
}else if (searchterm == "min"){
min = Math.min.apply(Math,array.map(function(e){return e.scanval;}))
}else
{document.getElementById("demo").innerHTML = "Only max and min available";}
if(searchterm == "max"){
document.getElementById("demo").innerHTML = "Search: " + scanval +" "+ "Value: " + max;
}
if(searchterm == "min"){
document.getElementById("demo").innerHTML = "Search: " + scanval +" "+ "Value: " + min;
}
}
</script>
</body>
</html>
The above should give me a and 6 or b and 3 as results. However I get NaN as result for the value part. When using "return e.a" in the Math section and only having a as keys it works.
I want to be able to determin the max or min value of a key I enter as parameter to the function.
Hope you can help me here.
Thanks in advance.
TheVagabond
There are some naming mess in your code. For example scanvalue is name of your function but you are trying to reach it as a parameter of e(e.scanvalue). I should be scanval. But still there are some problems. You can't reach property "a" or "b" of e if e.scanval. You're trying to reach variable of variable.
Then, you should use e[scanval]. It returns you to value of "a" or "b". But if object doesn't have one of them? Then you should add "|| 0" to get correct value. (Instead of NaN or undefined) It means that; use e[scanval] if its valid, if not use 0.
Use this;
return e[scanval] || 0;
If your boundaries include some negative values, use something like -9999 or -Infinity.
You are getting Nan because e.scanvalue returns undefined in your case.
Try using custom function.
function getValue(arr){
var res = [];
for(var j = 0; j < arr.length; j++)
{
for(var anItem in arr[j])
{
res.push(arr[j][anItem]);
}
}
return res;
}
and call this function like
max = Math.max.apply(Math,getValue(array))
and
min = Math.min.apply(Math,getValue(array))
accordingly.
Hope this helps!!!!
I am trying to calculate the average of 3 values (each numbered from 1-10) that are selected by the user and then pass the results to an text input (for display as a graph).
It should be updating the new average every time one of the values is changed, but the averaging is not working correctly at all. I think that the loop is not resetting the values every time it runs- it's adding up the sum each time it runs, but not sure how to fix it.
Here is my code:
var sliders = $("#health1,#health2,#health3");
var elmt = [];
$(sliders).each(function () {
elmt.push($(this).attr('value'));
$("#health1,#health2,#health3").change(function () {
var sum = 0;
averageRisk();
});
});
function averageRisk() {
var sum = 0;
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i], 10);
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
elmt.push($(sliders).attr('value'));
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
Here is an example:
http://jsfiddle.net/pixelmix/783cfmnv/
Not sure but seems like a lot of extra work going. Main issue was you were building array of initial values and not getting the values each time they changed. That first .each got all the slider values and added them to elmt and continued to push new values on to after every change instead of just getting the current values every time. Did you want to accumulate all values over time?
Fiddle: http://jsfiddle.net/AtheistP3ace/783cfmnv/6/
$("#health1,#health2,#health3").on('change', function () {
averageRisk();
});
function averageRisk() {
var sum = 0;
var elmt = $("#health1,#health2,#health3");
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10); //don't forget to add the base
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
And as pointed out if you want to ignore updating things when the sum is NaN you can do this:
function averageRisk() {
var sum = 0;
var elmt = $("#health1,#health2,#health3");
for (var i = 0; i < elmt.length; i++) {
sum += parseInt(elmt[i].value, 10); //don't forget to add the base
}
if (isNaN(sum)) {
return false;
}
var avg = sum / elmt.length;
document.getElementById('healthLevel').value = +avg;
$('#healthLevel').val(avg).trigger('change');
console.log("Sum: " + sum);
console.log("Average: " + avg);
}
The problem is that you fill the elmt array at page loading.
When user changes the values, you do not refresh the elmt array. So the array used to compute the average is always the same, empty.
You have to recover the input values each time they are modified.
function averageRisk() {
var sum = 0;
// Re make the loop for getting all inputs values
$(sliders).each(function() {
var value = parseInt($(this).val(), 10);
sum += value;
});
var avg = sum/$(sliders).length;
$('#healthLevel').val(avg);
}
Working example : http://jsfiddle.net/783cfmnv/7/
PS : You can use the css class healthInput to select your inputs. If you add later other fields, you will not have to add the new input id to your jQuery selector.
I did this work, check it .
http://jsfiddle.net/783cfmnv/10/
$("#health1,#health2,#health3").change(function() {
var val1 = +slider1.val();
var val2 = +slider2.val();
var val3 = +slider3.val();
var avg = (val1 + val2 + val3) /3;
$("#healthLevel").val(avg);
});
For the sake of learning (I am very much a beginner), I am trying to write a function with that will generate random numbers according to three user inputed variables. The user can input how many random numbers to generate
var count = 10;
which numbers to avoid generating (seperated by commas)
var doNotInclude = (document.getElementById("doNotIncludeInput").value).split(",");
and what the highest number possible should be
var highestNumber = 10;
In theory, if the user inputed "1,2" for the doNotInclude variable, the function should create an array containing those two numbers and then each time it generates a random number, check it against the array to see if the number it generated is one of the numbers it isn't supposed to generate.
Unfortunately, it doesn't work. It creates the array as it should which I verified via console.log(), but it will still generate the numbers it isn't supposed to. Here's the full script:
document.getElementById("button").onclick = function() {
var total = 0,
average = 0,
random = 0,
count = parseInt(document.getElementById("countInput").value),
doNotInclude = document.getElementById("doNotIncludeInput").value).split(","),
highestNumber = parseInt(document.getElementById("highestNumberInput").value);
document.getElementById("text1").innerHTML = "";
for (var i = 0; i < count; i++) {
var proceed = false;
for (random = Math.floor(((Math.random()) * (highestNumber + 1))); proceed == false;) {
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
}
document.getElementById("text1").innerHTML = document.getElementById("text1").innerHTML + "<br />" + (i + 1) + ". " + random;
total = total + random;
if (i == (count - 1)) {
total / count;
document.getElementById("text").innerHTML = "Mean average = " + (Math.round(total / count));
}
}
}
The part that isn't working
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
the indexOf function, is something I read about on here, but I guess I don't fully understand it. By my understanding, it should check to see if any of the array values are the same as the random variable, and if not, then return "-1" and execute my code. It doesn't seem to be doing that though. I am super confused...would love some help. Is it possible the array is storing the numbers as strings instead of integers, and that is the problem?
Your if statement doesn't work because of coercion.
===-1
The array doNotInclude contains strings, but random is an integer value, === always compares value and type both.
You should either use ==. Or have the both types same.
Try this Fiddle
HTML
Count: <input id="countInput" value="10" /><br />
Do not include: <input id="doNotIncludeInput" value="0,1,2,3,4,5" /><br />
Highest Number: <input id="highestNumberInput" value="10" /><br />
<br />
<button type="button" id="button">Click to Run!</button><br />
<br />
Results:<br />
<div id="text1"></div>
Js
document.getElementById("button").onclick = function() {
var currentCount = 0;
var randomNumbers = [];
var count = parseInt(document.getElementById("countInput").value);
var doNotIncludeInput = document.getElementById("doNotIncludeInput").value.split(",");
var highestNumberInput = parseInt(document.getElementById("highestNumberInput").value);
var resultsElement = document.getElementById("text1");
resultsElement.innerHTML = "";
while(currentCount < count) {
var random = -1;
while(random === -1){
random = Math.floor((Math.random()) * (highestNumberInput + 1));
for(var i in doNotIncludeInput) {
if(parseInt(doNotIncludeInput[i]) === random){
random = -1;
}
}
if(random !== -1){
randomNumbers.push(random);
}
}
currentCount += 1;
}
resultsElement.innerHTML = randomNumbers.join(', ');
}