How to calculate the amount automatically using javascript - javascript

This is my function
function doMath() {
var counter; var nvalue; var amount;
var price=100;
nValue = document.getElementById("message").value;
amount=(nvalue*price);
document.getElementById("total").value=amount ;
}
My html
<input type="" name="message" id="message" onkeyup="doMath()"maxlength="60">message
<input type="text" name="total" id="total" maxlength="60"> amount
when user enter value into message field it should calculate the amount automatically and show it in amount field.
but while i entering the value it show NAN
its not calculating can anyone help me how to fix this .i m new to javascript

You declared your variable as nvalue but used nValue instead.
function doMath() {
var nValue; var amount;
var price=100;
nValue = document.getElementById("message").value;
amount=(nValue*price);
document.getElementById("total").value=amount ;
}

Your error is here:
amount = (nvalue * price);
It should be:
amount = (nValue * price);

Related

JavaScript calculate % of number in <input> field

I have 2 input fields:
<input id="input1" etc />
<input id="answer" etc />
What I want to do is when a user types in a numerical value (and to restrict them to numbers, no letters or special characters) in "input1" then "answer" input field shows what 0.0015% is of that number (i.e. user types in 35000 so in the answer field it would show 52.5 as that's 0.0015% of the number they entered). This is to be done real time with no submit or calculate button.
How can I do this?
You can do this way to add keyup event on your first input element. I've used vanilla JS though you've used jquery on your fiddle. My fiddle,
function myFunction() {
var inputVal = document.getElementById("input").value;
var answerVal = document.getElementById("answer");
var percentage = (0.0015/100) * parseInt(inputVal,10) * 100;
if(inputVal !== ''){
answerVal.value = (Math.round( percentage * 100 ) / 100).toFixed(1)
}else{
answerVal.value = '';
}
}
input:<input id="input" type="number" onkeyup="myFunction()"/>
answer:<input id="answer" type="text" value=""/>
Your code is almost working perfectly, but it was not working in the given example by you and the reason for that is you have used parseint function of javascript which does not allow decimal values, and to restrict numbers you can use input type number.
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = $('#pointspossible').val();
var pEarned = $('#pointsgiven').val();
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned*pPos) / 100);
}
$('#pointsperc').val(perc);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id="pointspossible"/>
<input type='number' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>

Is it possible to run a single method with and without parameter in Javascript or jQuery?

I need to calculate the tax of total amount during onchange of quantity or price values.
Here is what I did:
function sum() {
var result1 = document.getElementById('result1').value;
var result2 = document.getElementById('result2').value;
var result3 = document.getElementById('result3').value;
var result4 = document.getElementById('result4').value;
var result5 = document.getElementById('result5').value;
var result6 = document.getElementById('result6').value;
var myResult = Number(result1) + Number(result2) + Number(result3) + Number(result4) + Number(result5) + Number(result6);
tax(myResult);
document.getElementById('sumvalue').value = myResult;
}
Here result1,2,3.. are sub total of items. Total amount is passed to the tax calculation.
function tax(tot) {
var taxval = document.getElementById('tax_val').value;
amt = (tot * taxval)/100 ;
document.getElementById('tax_amt').value = amt;
}
tax_amt is the Tax Amount final value. My requirement is: when I change the tax value, I need to run this same method.
Below element is the tax percentage holder. Whenever I change the value it must be frequently change the tax_total.
<input id="tax_val" type="number" value="15" oninput="tax(this_element_value)" >
In your case, I understand that you want realtime update of tax, when input is changed.
I would do something like this:
<input id="tax_val" type="number" value="15" oninput="onInputChanged(this)" >
function onInputChanged(elem) {
tax(elem.value);
}
First you can assign a class to all the elements variables (result1, result2, result3...) then add a event to this class like this:
$(".result").change(function () {
sum();
});
<div>
<input class="input-class" />
<input class="input-class" />
</div>
<script>
$('.input-class').on('change', function () {
/// here you need find input and there value then you can sum of these value.
});
</script>
check this. I think it helps you.

Currency converter doesn't work within a defined limit

I created a Bitcoin (BTC) to Canadian Dollar (CAD) converter that uses the current price from a different site, now I am trying to limit the values acceptable for the BTC/CAD inputs but it doesn't work.
The limits I want to set is $2 to $99.99 for CAD and the BTC equivalent for max/min but it doesn't want to work...
Fiddle:
https://jsfiddle.net/z735tswj/ all the relevant code is in the html tab or below
<input id="btcc" type="text" onkeyup="btcConvert()" onchange="btcCheck()">BTC</input>
<input id="cadc" type="text" onkeyup="cadConvert()" onchange="cadCheck()">CAD</input>
<br>
<br>
<script>
function btcConvert() {
var btc = document.getElementById("btcc").value;
var btcCalc = btc * price;
var btcCalc = btcCalc.toFixed(2);
document.getElementById("cadc").value = btcCalc;
btcCheck();
}
function cadConvert() {
var cad = document.getElementById("cadc").value;
var cadCalc = cad / price;
var cadCalc = cadCalc.toFixed(8);
document.getElementById("btcc").value = cadCalc;
cadCheck();
}
function btcCheck() {
if (btc.value < 0.001649) btc.value = 0.001649;
if (btc.value > 0.082259) btc.value = 0.082259;
btcConvert();
}
function cadCheck() {
if (cad.value < 2) cad.value = 2;
if (cad.value >= 100) cad.value = 99.99;
cadConvert();
}
</script>
Got it working, your script was not passing the input value to cadCheck()
I just made a few edits to get it to work. cadCheck() will get the value of the input before running cadConvert().
function cadCheck(input) {
if (input.value < 2) input.value = 2;
if (input.value >= 100) input.value = 99.99;
cadConvert();
}
I also took out the onkeyup="cadConvert() because you are calling that in cadCheck() and added this("this" being the input's value) to onchange="cadCheck().
new html <input id="cadc" type="text" onchange="cadCheck(this)">CAD</input>
Here is my code https://jsfiddle.net/so7s9efr/
Don't mean to be the "just use this" guy, but currency conversion is a common, solved problem and there are many good solutions out there.
A good one is money.js
Was working on a fiddle solution, but Paul Allen's works fine.

How do I use a form input number as a Javascript variable?

<form>
<input type="text" name="" value="">
</form>
//for loop used to calculate balance after payment(x) and interest
// the variable I want defined from the form input box
for(i = 6000; i>=10; i = i * (1+0.2/26)-x){
var x = 155;
document.write("Balance " + " $" + i + "<br/><br/>");
}
You could attach a pseudo class in your input element and then get the value inserted like below:
<input type="text" name="" value="" class="js-interest">
<script>
var ele = document.getElementsByClassName("js-interest")[0];
var value = parseFloat(ele.value);
</script>
You can try document.getElementById('input_id').value and then use parseInt to get it as an integer, as below:
var x = parseFloat(document.getElementsByName('number_box').value);
Also, the html must look something like this:
<form>
<input type="text" name="number_box" value="">
</form>
Optionally, instead of document.getElementsByName() you can use document.getElementById() or document.getElementsByClassName().
Update:
If I am not wrong
for(i = 6000; i>=10; i = i * (1+0.2/26)-x){
var x = 155;
document.write("Balance " + " $" + i + "<br/><br/>");
}
It seems like you are writing to the DOM inside a for loop don't do that calculate your ANS and then write to the DOM.
Also, don't read the data from input inside the loop. (You will be repeatedly reading and writing the data thats not good.)
Your for loop for(i = 6000; i>=10; i = i * (1+0.2/26)-x) is incrementing using some expression i = i * (1+0.2/26)-x (make sure it is bound to the condition and its not making the loop infinite)
You can select the value from the input field using the following code
x = parseInt(document.querySelector('form input[name="my_number"]').value);
document.querySelector it uses CSS style selector. So, to select the input field inside your form. I have added a name to the form as name="my_number"
<input type="text" name="my_number" value="">
now using the css selector form input[name="my_number"] it select the input field inside a form with name "my_number"
The whole Query selector that will return the input element is this,
document.querySelector('form input[name="my_number"]')
now to get the value of the input field you have to read the value property of the input field.
document.querySelector('form input[name="my_number"]').value
This will return your input value as string.
Now, we need to parse that string value to a Integer format.
We do that like this, (using parseInt)
parseInt(document.querySelector('form input[name="my_number"]').value)
I have added you code in a function named calc
function calc() {
var x = parseInt(document.querySelector('form input[name="my_number"]').value);
var ans= calculate_your_value(x);
document.write("Balance " + " $" + ans + "<br/><br/>");
}
I have fetched the answer from a function named get calculated answer and its good to do this way.
function calculate_your_value(x){
// calculate the ans the for loop seems buggy
//for (i = 6000; i >= 10; i = i * (1 + 0.2 / 26) - x) {}
return x; //dummy ans
}
It is called when you submit the form.
To do that I have added onsubmit='calc()' on your form tag.
<form onsubmit='calc()'>
Additionally, I have added this function that submits the form when you have pressed enter too (Just for fun) :)
document.onkeydown=function(){
if(window.event.keyCode=='13'){
calc();
}
}
It just listens for key down press and check if it is a enter key (keycode is 13)
and calls the same calc function.
function calc() {
var x = parseInt(document.querySelector('form input[name="my_number"]').value);
var ans= calculate_your_value(x);
document.write("Balance " + " $" + ans + "<br/><br/>");
}
document.onkeydown = function() {
if (window.event.keyCode == '13') {
calc();
}
}
function calculate_your_value(x){
// calculate the ans the for loop seems buggy
//for (i = 6000; i >= 10; i = i * (1 + 0.2 / 26) - x) {}
return x; //dummy ans
}
<form onsubmit='calc()'>
<input type="text" name="my_number" value="">
<input type="submit" id="submitbtn" />
</form>

Input field not updating

I am trying to create a tip calculator using HTML and Javascript and each time the user changes the input field for the meal cost and tip amount, I have to validate whether or not it is a number and if it is, I have to cut down the number to 2 decimal places.
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = mealCost.toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = tipPercent.toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge);
var tipPercentage = document.getElementById(tipPercent);
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
I don't think it is taking the values that are edited using toFixed() and also the field tipAmount is showing NaN. How can I fix these errors?
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = parseInt(mealCost).toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = parseInt(tipPercent).toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge).value;
var tipPercentage = document.getElementById(tipPercent).value;
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
The validateMealCost and validateTipPercent functions lacked a parseInt to turn the values to numbers, and the calculateTipAmount function lacked a .value, turning it to NaN.
you need to parse the inputs - all the text inputs will provide strings and therefore cannot be compared to others numbers as a number not can they be in that form nor can they be used for calculations. Also note that even if you have used a number to do calculations, using .toFixed() will convert that number to a string.
For example - you will need to use parseInt or parseFloat which will return a number:
var tipPercent = parseInt(document.getElementById(tipPercent).value);
It is not updating because you need to declare the input before the script. So the simple fix for this would be to move the entire <script> tag to below the last occurrence of <input>.
You can emulate the result using the W3Schools Tryit Editor and pasting a snippet of your code:
<!DOCTYPE html>
<html>
<body>
The content of the body element is displayed in your browser.
<input type="text" id="tipAmount" />
<script>
document.getElementById('tipAmount').value = 5*5;
document.getElementById('tipAmount2').value = 5*5;
</script>
<input type="text" id="tipAmount2" />
</body>
</html>
Notice how the code only updates tipAmount and not tipAmount2.

Categories