Currently I am taking a value from a textbox and I want to ad all the integers below that value until you hit it. For example, if someone entered 3, I would want to add 3+2+1 then display that output.
function number4() {
box4 = document.getElementById('box4').value;
var total = 0;
for (var i = 0; i <= box4; i++) {
total += i;
};
alert(box4);
}
TYPE A NUMBER IN INPUT BOX: <input id='box4'>
<button onclick='number4()'>Alert sum of all integers from zero to box value
You're getting a string instead of a number
box4 = document.getElementById('box4').value; // -> '4'
Instead you would want to do this
box4 = Number(document.getElementById('box4').value); // -> 4
Also, You would want to alert total not box4 because total is the one being updated to have sum.
Box4 is storing the value of the input field.
alert(total)
Here's the working code:
function number4() {
const box4 = Number(document.getElementById('box4').value);
let total = 0;
for (let i = 0; i <= box4; i++) {
total += i;
};
alert(total);
}
TYPE A NUMBER IN INPUT BOX: <input id='box4'>
<button onclick='number4()'>Alert sum of all integers from zero to box value</button>
Related
I have an ecommerce product that I sell a box of assorted flavor bagels. The max amount of flavors per box is 12. I have a number input field for each of the 12 flavors as shown in the screenshot below.
I was able to use JavaScript to limit each individual number field from exceeding 12 but I am trying to make it where the other input fields disable once the total of all fields reaches the max of 12.
The code below is what I am using to get the total of all the fields.
but at the moment It only prevents the increase of number on an individual field once it reaches 12.
I want to prevent from adding more than 12 in total from all fields combined which will complete the box of 12 bagels
const totalMaxQty = 12;
getAllInputs.forEach(allInputs);
function allInputs(value) {
value.addEventListener("input", function(e) {
e.preventDefault();
sumTotal();
});
}
function sumTotal() {
let sumValue = document.querySelectorAll('.wapf-field-input input[type=number]');
let currentTotal = 0;
for (let i = 0; i < sumValue.length; i++) {
if (parseInt(sumValue[i].value)) {
currentTotal += parseInt(sumValue[i].value);
};
}
}
for (let i = 0; i < getAllInputs.length; i++) {
getAllInputs[i].max = totalMaxQty;
}
Vanilla JavaScript only, please.
I see that you are actually returning nothing in the sumTotal(), so simply calling it inside allInputs doesn't have any effect.
function sumTotal() {
let sumValue = document.querySelectorAll('.wapf-field-input input[type=number]');
let currentTotal = 0;
for (let i = 0; i < sumValue.length; i++) {
if (parseInt(sumValue[i].value)) {
currentTotal += parseInt(sumValue[i].value);
};
}
return currentTotal
}
About disabling the input fields, I suggest you use event delegation.
Put all the input fields and their labels in a container and set the event listener on it. So you don't need to set an event listener on each of the input fields in a for loop.
const container = document.getElementById("container")
container.addEventListener("input", handleInputs )
function handleInputs() {
let currentTotal=sumTotal()
if (currentTotal===12) {
for (let i = 0; i < getAllInputs.length; i++) {
getAllInputs[i].disabled = true;
}
}
}
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++;
}
}
I have a series of input boxes into which users will input numerical values to be stored in an array. I would like for these values to be added and their sum shown via an alert. However I cannot determine how to pass these values to the array via the click of a button like I hope to. Here is my code:
$('#check').click(function() {
var arr = [];
getSum = function() {
for ( i = 0; i < 100; i++){
arr[i] =
$('input:number').map(function(){
return this.value;
});
}
var sum = 0;
var n = arr.length;
for(var i = 0; i < n ; i++) {
sum += parseInt(arr[i]);
}
alert(sum);
}
getSum();
});
with HTML markup:
<input type="number" id="field1" />
<input type="number" id="field2" />
<input type="number" id="field3" />
<button type="button" id="check">Calc</button>
Also, I have figured out how to dynamically add inputs so that the user may include more values in the sum, but I am not sure how this would affect the code. Would this still be sufficient?
I've shortened your code.
input[type=number] is a proper selector for what you're trying to do and it will find all new dynamically created inputs with type number.
$('#check').click(function() {
var sum = 0;
$('input[type=number]').each(function(i, input) {
sum += Number(input.value);
});
alert(sum);
});
var arr = [], sum = 0;
$("#check").click(function() {
$("input[type=number]").each(function() {
arr.push($(this).val());
sum += $(this).val();
});
});
I want to try and sum up distinct value from a list.. currently i am able to do so if theres only 2 similar record. If theres more than 2 i am not able to do the checking. Following is the javascript code:
function validateData(){
var total = document.frm.size.value;
var msg="";
var tbxA;
var tbxB;
var tbxA2;
var tbxB2;
var tbxC;
var totalValue =0;
var repeatedValue= 0;
var row = 0;
var row2 = 0;
for(var i=0; i<parseInt(total); i++){
tbxA = document.getElementById('tbx_A'+i).value;
tbxB = document.getElementById('tbx_B'+i).value-0;
tbxC = document.getElementById('tbx_C'+i).value;
for(var j=i+1; j<parseInt(total); j++){
tbxA2 = document.getElementById('tbx_A'+j).value;
tbxB2 = document.getElementById('tbx_B'+j).value-0;
if (tbxA==tbxA2) {
totalValue = tbxB + tbxB2;
}
if (totalValue != tbxC) {
repeatedValue= 1;
row = i;
row2 = j;
msg+="*total value does not add up at row " +(row2+1);
break;
}
}
if(repeatedValue== 1){
break;
}
}
return msg;
}
For example A:type of fruit, B: total of each fruit, C: how many bought at a time
total of C should be equal to B. i.e Apple: 3+3+4 = 10. So if the total is not equals to 10 it should prompt me an error.
A B C
Apple 10 3
Orange 10 10
Apple - 3
Apple - 4
My code above will prompt error bt it doesnt go beyond 2nd occurence of Apple.
So yes, how should i go about to ensure it loop through the whole list to sum up all similar values?
Thanks in advance for any possible help!
Try this:
var total = +document.frm.size.value,
data = {};
for(var i=0; i<total; ++i) {
var key = document.getElementById('tbx_A'+i).value;
data[key] = data[key] || {B:0, C:0};
data[key].B += +document.getElementById('tbx_B'+i).value || 0;
data[key].C += +document.getElementById('tbx_C'+i).value || 0;
}
for(var i in data) {
if(data.hasOwnProperty(i) && data[i].B != data[i].C) {
return "total value does not add up";
}
}
return "";
Some comments:
parseInt (and parseFloat) is very slow. + operator before string converts it to a number much faster. But if you really want to make sure the numbers are integers, use Math.floor(), Math.round(), Math.ceil() or the faster but illegible |0.
In case you really want parseInt (e.g. you want to convert '123foobar' into 123), always use a radix. For example: parseInt('123', 10)
Avoid doing calculations at the condition of a loop, because they run at each iteration. Just do the calculation once before the loop and save the result in a variable.
I am having the
table which contains the table like
items price quantity total
apple 100 2 200
orange 200 2 600
grand total=600.
item fields are dropdown when drop down changes the price will be changed and total value and grandtotal also changed. My problem is when selecting apple and orange again go to apple change the item my grand total is not changing.
My Javascript code:
function totalprice(element, price) {
var elementid = element.id;
var expr = elementid.substring(elementid.indexOf(":") + 1, elementid.length);
var quantity = document.getElementById("quantity:" + expr).value;
var price = document.getElementById("price:" + expr).value;
if (quantity > 0) {
document.getElementById("total:" + expr).value = (parseInt(quantity)) * (parseInt(price));
var grandtotal = document.getElementById("total:" + expr).value;
var gtot = 0;
var amount = 0;
for (var i = 0; i <= expr; i++) {
//document.getElementById("total").value="";
gtot = document.getElementById("total:" + expr).value;
amount = parseInt(gtot) + parseInt(amount);
}
document.getElementById("total").value = amount;
}
return true;
}
I know the mistake is in for loop only it is simple one but i dont know how to solve.
I got the solution for this using table rows length and use that length to my for loop now my code is like
function totalprice(element,price)
{
var elementid=element.id;
var expr = elementid.substring(elementid.indexOf(":") + 1, elementid.length);
var quantity = document.getElementById("quantity:"+expr).value;
var price = document.getElementById("price:" + expr).value;
if(quantity >0)
{
document.getElementById("total:"+ expr ).value= (parseInt(quantity))*(parseInt(price));
//var grandtotal =document.getElementById("total:"+expr).value;
//var grandtotal = document.getElementsByClassName("total"+expr);
var rowcount = document.getElementById('table').rows.length;
var grandtotal = 0;
var finalamount = 0;
for(var i=1; i<rowcount; i++)
{
grandtotal=document.getElementById("total:"+i).value;
finalamount = parseInt(grandtotal) + parseInt(finalamount);
}
document.getElementById("total").value=finalamount;
}
return true;
}
Here is code what you need:
Java Script:
<script>
function getVal(e){
// for text
alert(e.options[e.selectedIndex].innerHTML);
// for value
alert(e.options[e.selectedIndex].value);
}
</script>
HTML:
<select name="sel" id="sel" onchange='getVal(this);'>
<option value="1">Apple</option>
<option value="2">Banana</option>
<option value="3">Cat</option>
</select>
I see two errors in your for loop, first you forgot to use i in your getElement so you're only going through the same field multiple times, second, you're only looping through the inputs previous to the field that was updated (i<=expr), when you actually want to go through all the "total" fields to get the grand total, I would suggest giving a class to all your total fields and then use this code for your loop
var total_fields = document.getElementsByClassName('total');
for (var i = 0; i < total_fields.length; i++) {
gtot = total_fields[i].value;
amount+= parseInt(gtot);
}
document.getElementById("total").value = amount;
I think the problem relies here:
"My problem is when selecting apple and orange again"
Because I don't see in your code that you are actually updating the elements id when you calculate the total.
So... If you do:
gtot = document.getElementById("total:" + expr).value;
First time will work, because expr var is the original one, then, gtot is the right element id
but...
...when you do a second change, that var has a different value now... and gtot will not match your element id to recalculate the new value. (or in worst case, will match another and update the wrong one)