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++;
}
}
Related
This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 4 years ago.
I have made a piece of code that generates a random code of 12 characters. I am using Math.random and for-loops to do this. On the page you can write in an input how many codes you want.
What I want to do is save the generated codes in an array, however I can't do this because the for-loop and Math.random creates the code number by number and places them after each other. How can I add the whole 12 digit code to my array (so I can use it later)?
I've tried array.push with no luck. What works is outputting the numbers to DOM object in HTML, like this:
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
But that doesn't put the 12 digit code into a variable. I've also tried this:
var codeNumber = "";
codeNumber += mathRandom;
But that ends up in the variable value having only 1 digit.
<input type="number" id="numberOfCodes">
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
<script>
var numberOfCodes = document.querySelector("#numberOfCodes");
var arr = [];
function codeGen() {
x = numberOfCodes.value;
for (a = 0; a < x; a++) {
generate();
console.log("Generated code");
}
}
function generate() {
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
}
</script>
</div>
</body>
</html>
I expect the codes created (after some changes) to be added to the array, so that I can later use the codes on the page. Each individual 12-digit code needs to have its own place in the array.
This should work:
var result = [], stringResult;
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
result.push(mathRandom);
}
stringResult = result.join(''); // concatenates all the elements
console.log(stringResult);
The problem with your code is that + sign attempts to determine types of the operands and to choose the right operation, concatenation or addition. When adding stuff to innerHtml it treats the number as string. That is why it worked.
You'll want to refactor things so generating a single code is encapsulated in a single function (generate() here), then use that function's output, like this. (I hope the comments are enlightening enough.)
var numberOfCodes = document.querySelector("#numberOfCodes");
var resultDiv = document.querySelector("#result");
function codeGen() {
var nToGenerate = parseInt(numberOfCodes.value);
for (var a = 0; a < nToGenerate; a++) {
var code = generate(); // generate a code
// you could put the code in an array here!
// for the time being, let's just put it in a new <div>
var el = document.createElement("div");
el.innerHTML = code;
resultDiv.appendChild(el);
}
}
function generate() {
var code = ""; // define a local variable to hold the code
for (i = 0; i < 12; i++) { // loop 12 times...
code += Math.floor(Math.random() * 9); // append the digit...
}
return code; // and return the value of the local variable
}
<input type="number" id="numberOfCodes" value=8>
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
As this answer shows, this should work for you:
function makeRandCode() {
var code = "";
var ints = "1234567890";
for (var i = 0; i < 12; i++) {
code += ints.charAt(Math.floor(Math.random() * ints.length));
}
return code;
}
console.log(makeRandCode());
The problem is that you are adding numbers and what you really want is to concatenate them, the solution is to transform those numbers into String, then save them in the variable where you want to store them. An example:
2 + 2 = 4 and '2'+'2'='22'
Just use .toString() before save it in to the variable.
Someone showed me the following code which generates 3 random numbers between 1 and 10:
var limit = 10,
amount = 3,
lower_bound = 1,
upper_bound = 10,
unique_random_numbers = [];
if (amount > limit) limit = amount; //Infinite loop if you want more unique
//Natural numbers than exist in a
// given range
while (unique_random_numbers.length < limit) {
var random_number = Math.floor(Math.random()*(upper_bound - lower_bound) + lower_bound);
if (unique_random_numbers.indexOf(random_number) == -1) {
// Yay! new random number
unique_random_numbers.push( random_number );
}
}
//
How could I make these numbers appear in place of elements with a corresponding class? The code below is clearly wrong, but hopefully it illustrates what I'm trying to achieve:
<script type='text/javascript'>
var random_number1 = random_number1();
$('.random_number1').html(random_number1);
var random_number2 = random_number2();
$('.random_number2').html(random_number2);
</script>
<span class="random_number1"></span> <span class = "random_number2"></span>
assuming you had a div with id of numbers and the array unique_random_numbers, you'd populate it this way, assuming you have jquery reference:
for ( i = 0; i < unique_random_numbers.length; i++)
{
$("#Numbers").html($("#Numbers").html() +"<span>" + unique_random_numbers[i] + "</span><br/>");
}
I got different buttons that looks like down below (ranging from 1 to 9)
<button type="button" onclick="calculatorNumber(1)">
It leads up the following function:
function calculatorNumber(i) {
myNumbers.push(i);
var x = document.getElementById("screen").innerHTML = myNumbers.join("");
But its not working quite as I'd like it to. If i press number 3 once and then number 4, 3 & 4 is stored in the array at [0] and [1] however i would like them to be stored at the same place and as 34. Any ideas?
I've tried to enhance the function by the following code but it does not seem to work:
function calculatorNumber(i) {
myNumbers.push(i);
var x = document.getElementById("screen").innerHTML = myNumbers.join(""); //joining them together without comma
myNumbers = []; //then empty the array altogether
myNumbers.push(x); // and then push the new value in
You don't need an array of numbers. It's just one number:
theOneNumber = theOneNumber * 10 + i;
So you start with 0.
Press 3 => number is 3
Press 4 => number is 34
Press 5 => number is 345
You need to keep the numbers pushed in. Please delete this line:
myNumbers = []; //then empty the array altogether
Working example
var myNumbers = [];
function calculatorNumber(i) {
myNumbers.push(i);
document.getElementById("screen").innerHTML = myNumbers.join("");
}
function cl() {
myNumbers = [];
document.getElementById("screen").innerHTML = "";
}
<div id="screen"></div><br>
<button type="button" onclick="calculatorNumber(1)">1</button>
<button type="button" onclick="calculatorNumber(2)">2</button>
<button type="button" onclick="cl()">CL</button>
With numbers
var myNumbers = [0], operator = [];
function calculatorNumber(i) {
myNumbers[myNumbers.length - 1] = myNumbers[myNumbers.length - 1] *10 + i;
updateScreen();
}
function cl() {
myNumbers[myNumbers.length - 1] = 0;
updateScreen();
}
function plus() {
operator.push(p);
myNumbers.push(0);
updateScreen();
}
function p(b, a) {
myNumbers.push(a + b);
}
function equal() {
operator.length && operator.pop()(myNumbers.pop(), myNumbers.pop());
updateScreen();
}
function updateScreen() {
document.getElementById("screen").innerHTML = myNumbers[myNumbers.length - 1];
}
<div id="screen">0</div><br>
<button type="button" onclick="calculatorNumber(1)">1</button>
<button type="button" onclick="calculatorNumber(2)">2</button>
<button type="button" onclick="cl()">CL</button>
<button type="button" onclick="plus()">+</button>
<button type="button" onclick="equal()">=</button>
This solves your immediate problem:
var lastIndex = myNumbers.length - 1;
myNumbers[lastIndex] = myNumbers[lastIndex] * 10 + i;
However, I don't know how you want to handle operators.
You just have to concatenate the numbers in your array and convert them to string on the go.
For example:
myNums = [1, 2, 3]
var text = '';
for (i = 0; i < myNums.length; i++) {
text += myNums[i].toString();
}
returns '123'
then:
var x = document.getElementById("screen").innerHTML = text;
Maybe you can split it into two functions:
var myNumbers = [];
text = '';
function getMyNumber(i){
myNumbers.push(i);
}
function getText(myNumbers){
for (i = 0; i < myNumbers.length; i++) {
text += myNumbers[i].toString();
}
}
Call these functions appropriately (loop through calling first, I don't know how you get the input though, then just call the second with myNumbers as argument) and then populate your 'screen' element. In this case both vars are global.
I hope it helps.
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(', ');
}
I want to be able to take the value from the calcOrderTotal input and then divide it and display the divided output in another input (for example, to show the Order Total price, and then what the order total 36 monthly lease price would be). I sort of attempted to do it with the "calc36Month" function, but I know it's not right.
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var serverPrice = $('.server-radio:checked').val() || 0;
var equipmentPrice = $('.equipment-radio:checked').val() || 0;
var underTotal = $("#under-box").val() || 0;
var orderTotal = parseFloat(CleanNumber(productSubtotal)) + parseFloat(CleanNumber(serverPrice)) + parseFloat(CleanNumber(equipmentPrice));
$("#order-total").val(CommaFormatted(orderTotal));
$("#fc-price").attr("value", orderTotal);
}
The calcOrderTotal function is then redirected to this HTML input and displays a dollar value (this does work):
<input type="text" class="total-box" value="$0" id="order-total" disabled="disabled" name="order-total"></input>
I want to be able to take the OrderTotal dollar value and divide it by 36 months and input the 36 month lease value into another input. Here is an example of what I'm looking for (I know this does not work):
function calc36Month() {
var 36Month = 0;
var orderTotal = $("#order-total").val() || 0;
var 36Month = parseFloat(CleanNumber(orderTotal)) / 36;
$("#36-monthly-total").val(CommaFormatted(36Month));
$("#fc-price").attr("value", 36Month);
}
How can I do this?
Here ya go:
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var serverPrice = $('.server-radio:checked').val() || 0;
var equipmentPrice = $('.equipment-radio:checked').val() || 0;
var underTotal = $("#under-box").val() || 0;
var orderTotal = parseFloat(CleanNumber(productSubtotal)) + parseFloat(CleanNumber(serverPrice)) + parseFloat(CleanNumber(equipmentPrice));
$("#order-total").val(CommaFormatted(orderTotal));
$("#fc-price").attr("value", orderTotal);
if (orderTotal > 0) {
calcMonthly(orderTotal);
}
}
EDIT: Edited per request.
function calcMonthly(total) {
var pmt1 = total / 36;
var pmt2 = total / 24;
var pmt3 = total / 12;
$("#monthly-36").val(CommaFormatted(pmt1));
$("#monthly-24").val(CommaFormatted(pmt2));
$("#monthly-12").val(CommaFormatted(pmt3));
//$("#fc-price").attr("value", pmt1); // what is the purpose of this?
}
Avoid using numeric digits as variable names, element ID's or CSS classes, or beginning any of the aforementioned references with a number. Begin all variable names, ID's and classes with a letter.