I have 3 input fields:
<input type="text" id ="v0" onkeyup="calculate()"><br>
<input type="text" id ="v1" onkeyup="calculate()"><br>
<input type="text" id="result" onkeyup="calculate()" readonly><br>
What I am trying to do is to count number from 1st input divided by number from 2nd input and displaying it in 3rd input.
function calculate(){
var result = document.getElementById('result');
var el, i = 0, total = 0;
while(el = document.getElementById('v'+(i++)) ) {
el.value = el.value.replace(/\\D/,"");
total = total + Number(el.value);
}
result.value = total;
if(document.getElementById('v0').value =="" && document.getElementById('v1').value ==""){
result.value ="";
}
}
Code is working fine for ADDING this input values, but I need to DIVIDE values from input fields.
I tried to replace "+" with "/" but it breaks the functionality.
You could try a simpler approach like this:
function calculate () {
var input1 = document.querySelector('#v0').value;
var input2 = document.querySelector('#v1').value;
if (input1 && input2) {
document.querySelector('#result').value = (input1 / input2).toFixed(2);
}
}
First of all you have to use "-" for subtraction. But if you want to perform division the problem is that during the first iteration you have total as 0, and it would be:
iteration[1]: 0/anything = 0
iteration[2]: 0/anything = 0
and so on
So you if you want to perform division you need initial value for total, it has to be the 1st input.
Hope that helps.
Related
I have a 'calculate' button that takes the quantity entered and multiplies it by the value of an item. JS is below:
function calculate() {
var totalPrice=0;
var price = document.getElementById("itemprice").innerHTML;
var quantity = document.getElementById("quantity").value;
totalPrice=price * quantity;
document.getElementById("totalamount").innerHTML="$" + totalPrice;
//document.write(price * quantity)
}
The above works perfectly for the calculate button. I'm looking to add to this
What I want to also achieve is adding an alert pop up should the "totalprice" result equals zero, a negative number, or NaN (if someone inputs a letter into the quantity box).
So adding to the above something like this:
if ("totalPrice" < 1, NaN)
alert (Please Enter valid quantity)
But I just don't seem to be able to make it work.
totalPrice is variable, if you put it in quotes its a string
if you need 2 conditions in if use || an or operator in your case. Also read: javascript multiple OR conditions in IF statement
Read here how to check for NaN
totalPrice = "not a number"
if (isNaN(totalPrice) || totalPrice < 1) {
alert("Please Enter valid quantity")
}
So you should use:
function calculate() {
var totalPrice = 0;
var price = document.getElementById("itemprice").innerHTML;
var quantity = document.getElementById("quantity").value;
totalPrice = price * quantity;
if (isNaN(totalPrice) || totalPrice < 1) {
alert("Please Enter valid quantity")
} else {
document.getElementById("totalamount").innerHTML = "$" + totalPrice;
}
}
hi im very new to javascript and stuck doing my homework. My question is how do I add multiple inputs together in a do while loop? I am supposed to get all the inputs added together then divided by the amount of inputs to get the average. For example if the user were to input 7, 3, 5 and 2 then the answer will be 4.25.This is what I have so far.
var prompt;
var input = prompt("Please enter a number, input a negative number to stop");
var number = input >= 0;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
input = +prompt("Error enter a positive number to start");
}
do {
input = +prompt("Enter another number, a negative to stop");
sum += number;
//inputs added together goes here
} while (input >= 0);
alert(); //inputs added together divided by sum goes here
Hi try this version;
var num = 0, sum = 0, count = 0;
do {
num = parseInt(prompt('Enter Number'));
sum = num >= 0 ? sum+=num : sum;
count = num >= 0 ? count+=1: count; }
while(num >= 0);
console.log(sum + ' count is ' + count);
console.log(sum/count);
Basically I read from prompt, convert the input to integer, I sum the numbers if they are 0 or greater. I add 1 to the count if number is 0 or greater then I divide the sum by the count
Increase the value of sum2 to count the no input. And add a condition that if the user enter a negative value then the total will be divided by the no of inputs.
I have edited your code.
var prompt;
var input = prompt("Please enter a number, input a negative number to stop");
var number;
var alert;
var sum = 0;
var sum2 = 0;
while (input <= 0) {
input = +prompt("Error enter a positive number to start");
}
do {
input = +prompt("Enter another number, a negative to stop");
number=input;
alert(number);
sum += number;
sum2++;
if(input<0){
sum +=(-number);
alert("average"+(sum/(sum2-1)));
}
//inputs added together goes here
} while (input >= 0);
alert();
Hope it will help.
'use strict';
let input, sum = [];
do {
input = prompt("Enter another number, a negative to stop");
sum.push(input);
} while (input >= 0);
alert(sum.filter((a, b) => {return a + b}) / sum.length);
I have the need to calculate a price based on the number of words in a textarea. I will do my best to explain:
Flat fee = $35
Per prompt fee = $10
Per word fee = $.50 (after 30 words)
So I have the following textarea:
<textarea rows="10" class="form-control" name="voice-prompt-1" id="voice-prompt-1" placeholder="Type or paste your prompt here."></textarea>
<p>You have <span class="wordcount">0</span> words.</p>
And the following JS:
var perWord = '.50';
var flatFee = '35.00'
var promptPrice = '10.00';
function wordCount( val ){
return {
words : val.match(/\S+/g).length
}
}
var div = $('span.wordcount');
jQuery('textarea#voice-prompt-1').on('input', function($) {
var count = wordCount( this.value );
div.html(count.words);
additionalFees = perWord*count.words;
total = parseFloat(flatFee) + parseFloat(promptPrice) + parseFloat(additionalFees);
$('span.total').html(parseFloat(total.toString()).toFixed(2));
console.log(total);
});
My question is how do I get the perWord value to calculate only after 30 words is entered?
You want to first check that you have at least 30 words then, subtract 30 form the word count to get additiona fees.
if (count.words > 30) {
additionalFees = perWord * (count.words - 30);
}
Input fields:
<input name="qty1" id ="qty1" type="text" onblur="sum()"/>
<input name="qty2" id ="qty2" type="text" onblur="sum()"/>
<input name="qty3" id ="qty3" type="text" onblur="sum()"/>
<input name="qty4" id ="qty4" type="text" onblur="sum()"/>
<input name="total" id ="total" type="text"/>
Javascript:
<script type="text/javascript">
function sum(){
//grab the values
qty1 = document.getElementById('qty1').value;
qty2 = document.getElementById('qty2').value;
qty3 = document.getElementById('qty3').value;
qty4 = document.getElementById('qty4').value;
document.getElementById('total').value = parseFloat(qty1) + parseFloat(qty2) + parseFloat(qty3) + parseFloat(qty4);
}
</script>
Code displays 4 fields where user can insert a number, the 5th field recalculates the total e.g.: 1st field (qty1): 1, 2nd field (qty2): 2, 3rd field (qty3): 3, 4th field (qty4): 4, 5th field (total): 10 (1+2+3+4 = 10).
I would like to make this code more user friendly, so the script automatically treats empty fields as 0. Currenly if user leave field empty, the total shows "NaN"
Any advise?
Thanks,
Tom
use isNaN function to determine the value if value exist and is numeric or not and assign default value if it does not.
if(!isNan(qty4)){
qty=0;
}
Ironically, if you didn't use parseFloat, then you wouldn't get NaN in the first place. parseFloat('') returns NaN.
You should still convert the strings to numbers though, but instead of parseFloat, use the unary + operator. +'' returns 0, because the mathematical value of an empty string is 0:
function sum(){
//grab the values
var qty1 = +document.getElementById('qty1').value;
var qty2 = +document.getElementById('qty2').value;
var qty3 = +document.getElementById('qty3').value;
var qty4 = +document.getElementById('qty4').value;
document.getElementById('total').value = qty1 + qty2 + qty3 + qty4;
}
Now you only get NaN if the the user provides a value that cannot be converted to a number, such as abc. To fix that, you can indeed use isNaN.
Here is fixed and more concise version of your code, making use of reduce:
function sum(){
document.getElementById('total').value =
[1, 2, 3, 4].reduce(function(total, id) {
var v = +document.getElementById('qty'+id).value;
return total + isNan(v) ? 0 : v;
}, 0);
}
function sum(){
//grab the values
qty1 = document.getElementById('qty1').value || 0;
qty2 = document.getElementById('qty2').value || 0;
qty3 = document.getElementById('qty3').value || 0;
qty4 = document.getElementById('qty4').value || 0;
document.getElementById('total').value = parseFloat(qty1) + parseFloat(qty2) + parseFloat(qty3) + parseFloat(qty4);
}
I have a javascript as below:
function calculateBill(id,price)
{
var t = document.getElementById('total').value;
var qty = document.getElementById('qty_'+id).value;
var total = qty * price;
var tcost = Number(t) + Number(total);
document.getElementById('total').value = '';
//tcost = parseFloat(tcost);
document.getElementById('total').value = tcost.toFixed( 0 ) ;
}
This function is called in a onchange event
<input type="text" id = "qty_<?php echo $i2; ?>" name="qty_<?php echo $i2; ?>" onchange="calculateBill('<?php echo $i2; ?>','<?php echo round($r2[$i2]['ret_price'],2); ?>')" />
Since its an onchange event, it calculates the total cost whenever I change the value.
Now my problem is when I want to update the previously entered value, it calculates the new amount to old total.
( Suppose previous value for quantity is 2 , rate is 5 so total
5 * 2 = 10
Hence total is 10 from javascript function
Now if I edit the quanity to 1, insted of 5*1 = 5, I will get 10 + ( 5 * 1) = 15 !
)
How can I prevent this?
Use hidden value for old total like
<input type="hidden" id="old_total" value="<?=$total?>">
Just for the calculation use id old_total
var t = document.getElementById('old_total').value;
And to display output use id total
document.getElementById('total').value = tcost.toFixed( 0 ) ;
Have a hidden field
<input type="hidden" id="hidden_total"/>
Make Hidden field value to have the initial total value when the form loaded.
now, inside the function, use the hidden_total value to add and set it to 0 once you are done with computing.
function calculateBill(id,price)
{
var t = document.getElementById('hidden_total').value;
var qty = document.getElementById('qty_'+id).value;
var total = qty * price;
var tcost = Number(t) + Number(total);
document.getElementById('total').value = tcost.toFixed( 0 ) ;
}
You might need to update the reset the value of hidden field once you have computed, depending on your need. In that case, add the following in the last line;
document.getElementById('hidden_total').value = '';