Display vat value in text box - javascript

Does anyone know why I'm getting a value NaN in the vat input box? When I enter a value of qty it always gives me a NaN value.
$('#sales_qty').keyup(function(){
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
var vat = 0.12;
var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2));
$('#sales_vat').val((sales_total * vat).toFixed(2));
});
JSFiddle: https://jsfiddle.net/yv6zks1g/

Because sales_total is the element itself, (not the value). you should add another val() at the end to get the value.
$('#sales_qty').keyup(function(){
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
var vat = 0.12;
var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2)).val();
$('#sales_vat').val((sales_total * vat).toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="sales_qty" type="text" placeholder="sales_qty" />
<input id="sales_sub_total" type="text" placeholder="sales_sub_total" />
<input id="sales_total" type="text" placeholder="sales_total" />
<input id="sales_vat" type="text" placeholder="sales_vat"/>

i think its because of the var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2)); line.
instead of $('#sales_total').val((qty * sub_total).toFixed(2));
add var sales_total = (qty * sub_total).toFixed(2);

As in these two lines you are parsing float value from your input elements,
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
You need to set your inputs like these,
<input id="sales_qty" type="number" />
<input id="sales_sub_total" type="number" />
So that it is not possible to enter anything other than number. This will get you rid of the NaN problem.
Also you need to put
var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2)).val()

Its because you are not getting the real value of sales total input and you are just assigning a new value for it. On this line
var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2));
To fix it you have to get again the value of sales total input by using the val() method. Your code should look like this
$('#sales_qty').keyup(function(){
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
var vat = 0.12;
$('#sales_total').val((qty * sub_total).toFixed(2)); // assign the value
var sales_total = $('#sales_total').val() // grab the value
$('#sales_vat').val((sales_total * vat).toFixed(2));
});

Related

Nan proplem in JS

I have some problem with my js code which when I run the code it show me a NaN error, I have a function that calculate something.
Example:
<p id = "total "></p>
total = num1 *num2;
document.getElementById("total").innerHTML = total;
And it works fine but when I create a new function to calculate the discount
var price = document.getElementById("total").value;
discount = total *0.10;
It shows a NaN, I tried a lot of solution but it is still not working.
Can you help me?
I think you have a concept mistake, if the value is a HTML value, i mean, is inside of
<p id="this_is_the_element">123456789</p>
You can get that value with javascript using the
var number = document.getElementById('this_is_the_element').innerHTML
now the number variable will have inside "123456789" as a STRING
But if you are using an input you should use
var number = document.getElementById('this_is_the_element').value
Now, try this. First try to avoid the parseInt, instead use Number.
Define a function
var discount = function(){
var price = Number(document.getElementById("total").innerHTML);
return price*0.1;
}
If you want to do it on new sintax use this
const discount = () => {
const price = Number(document.getElementById("total").value);
return price*0.1;
}
There are few issues in your code:
There is no value property of p element. To access the text in p element, you can use either textContent or innerText.
By default the text is of type string. Multiplying string with number gives you NaN. You have to convert that to number before doing any arithmetic operation.
var num1 = 5;
var num2 = 20;
var total = num1 *num2;
document.getElementById("total").textContent = total;
var elTotal = Number(document.getElementById("total").textContent);
var discount = elTotal * 0.10;
console.log(discount)
<p id = "total"></p>
When you pull the value, it's a String, and JavaScript for the most part will automatically do type conversion, but you can always wrap it in parseInt to force it to be a Number.
discount = parseInt(total) * 0.10;
You can also always run typeof total to verify if total is a Number or String, and you can run console.log(total) to visually verify the contents.
Also, your document.getElementById("total") references a paragraph element, which doesn't have .value property, so you should use innerText to get its value instead.
Demo
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
button1.addEventListener('click', function() {
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
total = parseInt(num1) * parseInt(num2);
document.getElementById("total").innerText = total;
});
button2.addEventListener('click', function() {
var total = document.getElementById("total").innerText;
discount = parseInt(total) * 0.10;
document.getElementById('discount').innerText = discount;
});
<input type="text" id="num1" /><br>
<input type="text" id="num2" /><br>
<button id="button1">Add</button>
<p id="total"></p>
<button id="button2">Discount</button>
<p id="discount"></p>
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

No clue what's wrong with my code [duplicate]

This question already has an answer here:
Javascript calculator keeps concatenating calculation results with first number entered for next calculation
(1 answer)
Closed 4 years ago.
I'm writing a program that takes two numbers, a subtotal and tax rate, and prints the sales tax and grand total. However, I've run into multiple problems writing it, so I've tried working backwards and dumbing it down to simply adding two numbers. Instead of adding the numbers, however, it is simply printing the two numbers side by side. Can anyone tell me what's wrong with my code?
https://codepen.io/anon/pen/jvNZox
HTML:
var subtotal = document.getElementById("subtotal");
var taxRate = document.getElementById("tax-rate");
var salesTax = document.getElementById("sales-tax");
var total = document.getElementById("total");
subtotal.addEventListener("input", calc);
taxRate.addEventListener("input", calc);
function calc()
{
var sub = (subtotal.value) || 0;
var tax = (taxRate.value) || 0;
total.innerHTML = sub + tax;
}
JS:
var subtotal = document.getElementById("subtotal");
var taxRate = document.getElementById("tax-rate");
var salesTax = document.getElementById("sales-tax");
var total = document.getElementById("total");
subtotal.addEventListener("input", calc);
taxRate.addEventListener("input", calc);
function calc()
{
var sub = (subtotal.value) || 0;
var tax = (taxRate.value) || 0;
total.innerHTML = sub + tax;
}
EDIT: My bad, forgot to add parseFloat before my value checks. Same problem still stands for when I go back to my original code:
var subtotal = document.getElementById("subtotal");
var taxRate = document.getElementById("tax-rate");
var salesTax = document.getElementById("sales-tax");
var total = document.getElementById("total");
subtotal.addEventListener("input", calc);
taxRate.addEventListener("input", calc);
function calc()
{
var sub = parseFloat(subtotal.value) || 0;
var tax = parseFloat(taxRate.value) || 0;
salesTax.innerHTML = sub * (tax /100);
total = sub + salesTax.innerHTML;
}
You're bumping into the fact that the values are strings, and you can use + to concatenate strings as well as add up numbers.
Parse the number strings into actual Numbers first:
function calc()
{
var sub = parseFloat(subtotal.value || 0);
var tax = parseFloat(taxRate.value || 0);
total.innerHTML = sub + tax;
}
You need to take the numerical value of the strings by using an unary plus +, for example.
This approach has the advantage, if a nonconvertable string is supplied, a NaN value is taken as falsy value and together with logical OR ||, you get zero as default value.
var sub = +subtotal.value || 0;
var tax = +taxRate.value || 0;
JavaScript considers the values as two strings and thus combines them.
Do something like this:
var subtotal = document.getElementById("subtotal");
var taxRate = document.getElementById("tax-rate");
var total = document.getElementById("total");
subtotal.addEventListener("input", calc);
taxRate.addEventListener("input", calc);
function calc() {
var sub = Number(subtotal.value) || 0;
var tax = Number(taxRate.value) || 0;
total.innerHTML = sub + tax;
}
<p> Subtotal: <input id = "subtotal"></p>
<p> Tax Rate: <input id = "tax-rate"></p>
<p id = "total"></p>
Change the logic for addition to below as previously it was considering it as a JavaScript string and instead of summing it was concatenating it. Explicitly converting it to an integer/double will prevent this. '||' handles non-numeric data in text field.
var subtotal = document.getElementById("subtotal");
var taxRate = document.getElementById("tax-rate");
var salesTax = document.getElementById("sales-tax");
var total = document.getElementById("total");
subtotal.addEventListener("input", calc);
taxRate.addEventListener("input", calc);
function calc()
{
var sub = parseFloat(subtotal.value) || 0;
var tax = parseFloat(taxRate.value) || 0;
salesTax.innerHTML = sub * (tax /100);
total.innerHTML = sub + parseFloat(salesTax.innerHTML|| 0);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p> Subtotal: <input id = "subtotal"></p>
<p> Tax Rate: <input id = "tax-rate"></p>
Total: <p id = "total"></p>
Sales tax: <p id = "sales-tax"></p>
</body>
</html>
You need to cast string value to integer type. To do it you could use parseInt function:
total.innerHTML = parseInt(sub) + parseInt(tax);

Pushing calculate sum to input

I want to push calculate sum those after Line total: display in input not in text.
I try add some input for example:
<input id="totalline" name="totalline" value="" />
and change this:
var calculate = function(el) {
var percent = el.find('input[name="percent[]"]').val();
var additional = el.find('input[name="additional[]"]').val();
var total = el.find('span.total');
var totalValue = ($("#weight").val() * percent / (100 - additional)).toFixed(2);
total.text(totalValue);
}
to this:
var calculate = function(el) {
var percent = el.find('input[name="percent[]"]').val();
var additional = el.find('input[name="additional[]"]').val();
var total = el.find('span.total');
var totalValue = ($("#weight").val() * percent / (100 - additional)).toFixed(2);
$('#totalline').val(totalValue); //<-this line changed
}
But this is not work like I want to.
Here is my fiddle.
You are trying to use an ID selector when there will be multiple elements with the same ID on the page (when you press the + button to add a new row). Simply change your selector to var total = el.find("[name='totalline']"); to ensure that you are always grabbing the correct input.
This is what it should look like:
HTML
Line total: <input name="totalline" value="" />
JS
var calculate = function(el) {
var percent = el.find('input[name="percent[]"]').val();
var additional = el.find('input[name="additional[]"]').val();
var total = el.find("[name='totalline']");
var totalValue = ($("#weight").val() * percent / (100 - additional)).toFixed(2);
total.val(totalValue);
}

Get Element by ID looping

I'm very new to javascript and i'm trying to loop through a variable to increment the id to 60. I have a form that users input numbers into then I need it to add them up. This is what I have so far.
<input type="text" onkeyup="addNumbers()" id="name1">
<input type="text" onkeyup="addNumbers()" id="name2">
<input type="text" onkeyup="addNumbers()" id="name3">
etc..
<input type="text" id="total" disabled>
function addNumbers(){
var name = []
for( var i = 0; i < 60; i++ ) {
name[i] = parseInt( document.getElementById("name" + i).value );
}
var total = document.getElementById('total').value = var;
}
</script>
I'm not getting any output from the above code, so i'm not sure what i am doing wrong here.
Try this. You have to iterate from index 1 to 60 and find the values of each input box. If value is valid, find sum and assign to total. JSFiddle
addNumbers = function(el){
var total = 0;
for( var i = 1; i <= 60; i++ ) {
var val = parseInt(document.getElementById("name" + i).value);
if(val>0){
total += val;
}
}
document.getElementById('total').value = total;
}
the best way is to add a class. then get elements by class name. that will give you a array of input elements. then you can easily iterate through the list to get value of input item and add them together. Its best to do this way so you dont have hardcode the number of inputs :)
var total = 0;
for( var i = 0; i < 60; i++ ) {
total += parseInt( document.getElementById("name" + i).value );
}
document.getElementById('total').value = total;
Try this. Your current code is close, but you are using an array which complicates things. Also you are assigning var to the element which is invalid.
Yeah.. got it.. you should pass the value from input text box on dom elements like..onclick="return functionname(this.value)" and use rest as it is in the javascript function as TGH answered.

Divide a function value by a number

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.

Categories