I got old code of my apps that using javascript to calculate something, the logic is if 1 textbox filled, another textbox automatic filled, and when the second textbox filled, that another textbox will return text1 - text2, maybe You can look at this fiddle:
HTML:
<label>Price Start</label>
<input type="number" class="form-control" placeholder="Total Harga Diberikan" required="required" name="price" onkeyup="calculate()" id="price" />
<br />
<label>Discount</label>
<input type="number" class="form-control" placeholder="Nominal Potongan" name="jmlvoucher" onkeyup="calculate()" id="jmlvoucher" />
<br />
<label>Total</label>
<input type="number" class="form-control" placeholder="Total yang harus dibayarkan" required="required" name="total" id="total" />
Javascript:
function calculate(){
var num1 = document.getElementById("price").value;
var num2 = document.getElementById("jmlvoucher").value;
var sum=parseFloat(num1)-parseFloat(num2);
document.getElementById('total').value=sum.toString();
}
http://jsfiddle.net/n4anv5qn/2/
Already try to check error, but there's no error. Try to run it, it doesn't works. Any idea why?
There indeed is an error being generated as keyup is fired.
Uncaught ReferenceError: calculate is not defined
On JSFiddle you've chosen to put your JavaScript into the onLoad function which is wrong. You should instead choose No Wrap
See http://jsfiddle.net/n4anv5qn/5/
As requested, this code is an example of how you can still calculate your Total if your Discount is not filled. Simply check to see if the value you grabbed from num2 is blank and set it to a default value.
function calculate(){
var num1 = document.getElementById("price").value;
var num2 = document.getElementById("jmlvoucher").value;
if (num2 == '')
num2 = '0';
var sum=parseFloat(num1)-parseFloat(num2);
document.getElementById('total').value=sum.toString();
}
You should use onchange instead of onkeyup. Also put your scripts right before the closing body tag.
Here's how to do it:
<label>Price Start</label>
<input type="number" class="form-control"name="price" onchange="calculate()" id="price" />
<br />
<label>Discount</label>
<input type="number" class="form-control" onchange="calculate()" id="jmlvoucher" />
<br />
<label>Total</label>
<input type="number" class="form-control" required="required" name="total" id="total" />
<script>
function calculate(){
var num1 = document.getElementById("price").value;
var num2 = document.getElementById("jmlvoucher").value;
var sum = parseFloat(num1) - parseFloat(num2);
document.getElementById('total').value = sum;
}
</script>
Related
Im very new to using javascript and to set up a basis to a program i need im trying to add two values from a text box together. Right now it is returning NaN when i invoke the javascript with my button.
<script>
function add()
{
num1 =parseInt( document.getElementById("num1").value);
num2 = parseInt(document.getElementById("num2").value);
document.getElementById("result").innerHTML= num1+num2;
}
</script>
</head>
<body>
<label id="num1">Number One:</label>
<input type="text" id="num1">
<br>
<label id="num2">Number Two</label>
<input type="text" id="num2">
<button onclick="add()">Calculate</button>
<span id="result"></span>
</body>
ID's must be unique. JS will act only on first ID in page.
You have non-unique ID's: label and input has same ID.
Replace <label id=""> to <label for="">
function add() {
num1 = parseInt(document.getElementById("num1").value);
num2 = parseInt(document.getElementById("num2").value);
document.getElementById("result").innerHTML = num1 + num2;
}
<label for="num1">Number One:</label>
<input type="text" id="num1"/>
<br/>
<label for="num2">Number Two</label>
<input type="text" id="num2"/>
<button onclick="add()">Calculate</button>
<span id="result"></span>
You've made a very silly mistake, your ids should always be unique.
Just remove the id attribute from the label tag.
To explain you what went wrong in your code is:
ids are meant to be unqiue, and when you were seacrhing the element by id, the JS was picking the label element, and the .value property on this element will return NaN, hence the output.
You can read more about ID here
I advise you not to declare javascript events inside html elements.
Also, you had an error in the html structure. You have indicated the same label id and intup twice. The identifier must be unique, and for the label you need to specify for - this means that this label refers to the corresponding input:
<label for="num1">Number One:</label>
<input type="text" id="num1">
let btn = document.querySelector('#btn');
let result = document.querySelector('#result');
btn.onclick = function() {
let num1 = parseInt(document.querySelector('#num1').value);
let num2 = parseInt(document.querySelector('#num2').value);
result.innerText = num1 + num2;
}
<body>
<label for="num1">Number One:</label>
<input type="text" id="num1">
<br>
<label for="num2">Number Two</label>
<input type="text" id="num2">
<button id="btn">Calculate</button>
<span id="result"></span>
</body>
This is a small part of a larger project. Why does it not output the total of the four number and display in the fifth text box?
<body>
<form action="acknolcupcard" method="post" name="CupCard" id="CupCard" target="_self">
<p></p>
<input name="OneH1" type="number" value="0" size="5" maxlength="5" onchange="calc"/>
<input name="OneH2" type="number" value="0" size="5" maxlength="5" onchange="calc"/>
<input name="OneH3" type="number" value="0" size="5" maxlength="5" onchange="calc"/>
<input name="OneH4" type="number" value="0" size="5" maxlength="5" onchange="calc"/>
<label for="S1TotH"></label>
<input type="text" name="S1TotH" id="S1TotH" value="0" size= "10" maxlength= "10"/>
</form>
<script type="text/javascript">
function calc(){
var S1TotH =<br />
document.getElementById('OneH1').value +
document.getElementById('OneH2').value +
document.getElementById('OneH3').value +
document.getElementById('OneH4').value;
document.getElementById('S1TotH').value = S1TotH;
}
</script>
</body>
You need to add id as an attribute:
<input id="OneH1" name="OneH1" type="number" value="0" size="5" maxlength="5" onchange="calc"/>
Also in order to call the method you should create a handler:
<script type="text/javascript">
function calc() {
// This doesn't work since <br/> has no type (e.g. var S1TotH = '<br />')
var S1TotH =<br />
/* This values need to be stored in a variable or used in some way
(e.g. var S1TotH = document.getElementById('OneH1').value + document...). But be careful because in this way you are concatenating the
values, not adding them. If you want to add them you
should convert them to numbers (e.g. parseFloat(document.getElementById('OneH1').value)) */
document.getElementById('OneH1').value +
document.getElementById('OneH2').value +
document.getElementById('OneH3').value +
document.getElementById('OneH4').value;
document.getElementById('S1TotH').value = S1TotH;
}
// use 'input' or 'change' event
document.querySelector('input').addEventListener('input', function () {
calc();
});
</script>
You don't call the function
Mentioning the name of a variable (even if the value of that variable is a function) doesn't call the function.
You need to put (argument, list) after it.
onchange="calc()"
Intrinsic event attributes have a bunch of problems though (e.g this one) and are best avoided.
You could use a delegated event listener instead.
function calc(event) {
const input = event.target;
console.log(input.value);
}
document.querySelector("form").addEventListener("change", calc);
<form>
<input type="number">
<input type="number">
<input type="number">
<input type="number">
</form>
You have no ids
Then it will run, but error, because you are using getElementById without having elements with id attributes.
You are concatenating not adding
Once you fix that, you will still not be adding up the values because + servers double duty as the concatenation operator and values are strings.
You need to convert them to numbers (e.g. with parseFloat).
This code should work, use oninput instead of onchange for live changes reflect, I resolved few other errors too.
<body>
<form action="acknolcupcard" method="post" name="CupCard" id="CupCard" target="_self">
<p></p>
<input name="OneH1" id="OneH1" type="number" value="0" size="5" maxlength="5" oninput="calc()"/>
<input name="OneH2" id="OneH2" type="number" value="0" size="5" maxlength="5" oninput="calc()"/>
<input name="OneH3" id="OneH3" type="number" value="0" size="5" maxlength="5" oninput="calc()"/>
<input name="OneH4" id="OneH4" type="number" value="0" size="5" maxlength="5" oninput="calc()"/>
<label for="S1TotH"></label>
<input type="text" name="S1TotH" id="S1TotH" value="0" size= "10" maxlength= "10"/>
</form>
<script type="text/javascript">
function calc(){
var S1TotH =
document.getElementById('OneH1').value +
document.getElementById('OneH2').value +
document.getElementById('OneH3').value +
document.getElementById('OneH4').value;
document.getElementById('S1TotH').value = S1TotH;
}
</script>
</body>
Above code will concate the values as these are strings values so far so you need to use the parseInt() function if you want to convert it into numbers
I have the following
<input type="text" class="form-control" name="total1" id="total1">
<input type="text" class="form-control" name="total1" id="total2">
I already get these two values using javascript.
but I want to display the result in a span like below or a P tag
<span id="sum">0</span>
I tried the following...but i want it to be auto...meaning once the input field if there, total should also appear
<script type="text/javascript" language="javascript" charset="utf-8">
function output(){
var value1 = document.getElementById('value1').value;
var value2 = document.getElementById('value2').value;
document.getElementById('result').innerHTML = parseInt(value1) + parseInt(value2);
}
function updateTextInput(val) {
document.getElementById('value2').value=val;
}
</script>
If you want to display the result you can simply use
Javascript : document.getElementById("sum").innerText = SumOfTwoValues
Jquery : $("#sum").text(SumOfTwoValues);
Please make sure you add required validations for the Summation value before assigning it.
Well first of you need some way to call the function output.
Now there are a few problems regarding the Ids of the elements, you have id="total1" but you are trying to call getElementById('value1').
same goes for total2 and sum.
Last I would add || 0 after your .value so incase 1 of the input's haven't been filled, then it set to 0, so we can use it as a number.
function output() {
var value1 = document.getElementById('total1').value || 0;
var value2 = document.getElementById('total2').value || 0;
document.getElementById('sum').innerHTML = parseInt(value1) + parseInt(value2);
}
<input type="text" class="form-control" oninput="output()" name="total1" id="total1">
<input type="text" class="form-control" oninput="output()" name="total1" id="total2">
<span id="sum">0</span>
With vanilla javascript
function a()
{
var a1=document.querySelectorAll('input')
let sum=0;
for(let i=0;i<a1.length;i++)
sum+=Number(a1[i].value)
document.querySelector('#e').innerHTML=sum
}
<input type="text" class="form-control" name="total1" id="total1" onchange="a()">
<input type="text" class="form-control" name="total1" id="total2" onchange="a()">
<p id="e"></p>
Calculation in one line of Javascript.
function calc() {
document.querySelector('#sum').innerHTML = [...document.querySelectorAll('input')].reduce((acc, input) => acc + Number(input.value), 0);
}
<input type="text" class="form-control" name="total1" id="total1" onchange="calc()">
<input type="text" class="form-control" name="total1" id="total2" onchange="calc()">
<p id="sum"></p>
I understand this may be a repeat question but I have been searching for ages and cant figure out why this isnt working.
I have 3 input fields, Subtotal, Vat and Total: I want to be able to populate the VAT and Total inpur fields with values when there is a value inputted in Subtotal and to show 2 decimal palces after. So:
4 would be 4.00
4.5 would be 4.50
HTML code for the input field:
<input name="subtotal" id="subtotal" type="number" maxlength="20" min="0" placeholder="00.00" onchange="vatCalculation();" />
<input name="vat" id="vat" type="number" maxlength="20" min="0" placeholder="00.00" readonly="true" />
<input name="total" id="total" type="number" maxlength="20" min="0" placeholder="00.00" readonly="true" />
And the javascript code I have at the moment is:
function vatCalculation() {
var subtotal = document.getElementById('subtotal').value;
var vat = parseFloat(parseFloat(subtotal) * parseFloat(0.2)).toFixed(2);
var total = parseFloat(parseFloat(subtotal) + parseFloat(vat)).toFixed(2);
document.getElementById('vat').value = vat;
document.getElementById('total').value = total;
}
I cant see where I am going wrong. When I enter 10 in the 'subtotal'input field the 'VAT' and 'Total' fields change to 2 and 12. But I want them to show 2.00 and 12.00. Screenshot below:
SOLUTION:
When using Firefox the input field of type="number" dont seem to work with javascript calculation. Workaround is to change it to a type="text" Like J Santosh as mentioned below and it works.
Found the issue . It is with <input type='number'> you change it to <input type='text'>
Working Fiddle
Input Type Number is not accepting decimals
Reference -1
Reference-2
Is this what you want? If so, you were pretty close. You just needed to add
document.getElementById('subtotal').value = parseFloat(subtotal).toFixed(2);
to your code as well.
function vatCalculation() {
var subtotal = document.getElementById('subtotal').value;
var vat = parseFloat(parseFloat(subtotal) * parseFloat(0.2)).toFixed(2);
var total = parseFloat(parseFloat(subtotal) + parseFloat(vat)).toFixed(2);
document.getElementById('subtotal').value = parseFloat(subtotal).toFixed(2);
document.getElementById('vat').value = vat;
document.getElementById('total').value = total;
}
<input name="subtotal" id="subtotal" type="text" maxlength="20" min="0" placeholder="00.00" onchange="vatCalculation();" />
<input name="vat" id="vat" type="text" maxlength="20" min="0" placeholder="00.00" readonly="true" />
<input name="total" id="total" type="text" maxlength="20" min="0" placeholder="00.00" readonly="true" />
(2.399).toFixed(2); will give you 2.40
But if you need 2.39 try
parseInt(2.399 * 100)/100
Hi i want to calculate two input field values and result will show in third input field so i want to write code in ajax page
<input id="a1" type="text" />
<input id="a2" type="text" onblur="Calculate();" />
<input id="a3" type="text" name="total_amt" value="" />
here javascript function
<script>
function Calculate()
{
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value=parseInt(resources) * parseInt(minutes);
document.form1.submit();
}
</script>
starting its working but nw its not working please help me
Thanks in Advance
Look this! Work it.
http://jsfiddle.net/op1u4ht7/2/
<input id="a1" type="text" />
<input id="a2" type="text" onblur="calculate()" />
<input id="a3" type="text" name="total_amt" />
calculate = function()
{
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value = parseInt(resources)*parseInt(minutes);
}
Try AutoCalculator https://github.com/JavscriptLab/autocalculate Calculate Inputs value and Output By using selector expressions
Just add an attribute for your output input like data-ac="(#firstinput+#secondinput)"
No Need of any initialization just add data-ac attribute only. It will find out dynamically added elements automatically
FOr add 'Rs' with Output just add inside curly bracket data-ac="{Rs}(#firstinput+#secondinput)"
My code is from an answer above. Special thank for you!
calculate = function (a, p, t) {
var amount = document.getElementById(a).value;
var price = document.getElementById(p).value;
document.getElementById(t).value = parseInt(amount)*parseInt(price);}
<input type="number" id="a0" onblur="calculate('a0', 'p0', 't0')">
<input type="number" id="p0" onblur="calculate('a0', 'p0', 't0')">
<input type="number" id="t0" >
<hr>
<input type="number" id="a1" onblur="calculate('a1', 'p1', 't1')">
<input type="number" id="p1" onblur="calculate('a1', 'p1', 't1')">
<input type="number" id="t1" >
put in you form id="form1"
the JavaScript is look like this.
calculate = function()
{
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value = parseInt(resources)*parseInt(minutes);
document.form1.submit();
}