I am new to javascript and am trying to get the calculation below to perform as the user inputs the values. I am unable to get the calculation to run at all and am not sure where I am going wrong. I would appreciate any assitance in solving the problem and understanding what is incorrect.
The inputs are:
<input name="ConceptEstimate_GrandTotal" type="text" />
<input name="ConceptEstimate_Exp" type="text" />
<input name="ConceptEstimate_Cap" type="text" />
<input name="ConceptEstimate_ProjMgmt" type="text" />
<input name="ConceptEstimate_PA" type="text" />
<input name="ConceptEstimate_DB" type="text" />
<input name="ConceptEstimate_Test" type="text" />
<input name="ConceptEstimate_Deploy" type="text" />
<input name="Capital_PA" type="text" disabled="disabled" />
<input name="Expense_PA" type="text" disabled="disabled" />
<input name="Capital_DB" type="text" disabled="disabled" />
<input name="Expense_DB" type="text" disabled="disabled" />
<input name="Capital_TD" type="text" disabled="disabled" />
<input name="Expense_TD" type="text" disabled="disabled" />
<input name="Capital_S" type="text" disabled="disabled" />
<input name="Expense_S" type="text" disabled="disabled" />
<input name="Capital_Total" type="text" disabled="disabled" />
<input name="Expense_Total" type="text" disabled="disabled" />
And the function is:
$(document).ready(function () {
$(".input").keyup(function () {
var a = +$("#ConceptEstimate_GrandTotal")[0].value;
var b = +$("#ConceptEstimate_Exp")[0].value;
var c = +$("#ConceptEstimate_Cap")[0].value;
var d = +$("#ConceptEstimate_ProjMgmt")[0].value;
var e = +$("#ConceptEstimate_PA")[0].value;
var f = +$("#ConceptEstimate_DB")[0].value;
var g = +$("#ConceptEstimate_Test")[0].value;
var h = +$("#ConceptEstimate_Deploy")[0].value;
$("#Capital_PA")[0].value = a * (c/100) * (e/100);
$("#Expense_PA")[0].value = a * (b/100) * (e/100);
$("#Capital_DB")[0].value = a * (c/100) * (f/100);
$("#Expense_DB")[0].value = a * (b/100) * (f/100);
$("#Capital_TD")[0].value = (a * (c/100) * (g/100)) + (a * (c/100) * (h/100));
$("#Expense_TD")[0].value = (a * (b/100) * (g/100)) + (a * (b/100) * (h/100));
$("#Capital_S")[0].value = a * (c/100) * (d/100);
$("#Expense_S")[0].value = a * (b/100) * (d/100);
});
});
There's a lot wrong here.
1) You're mixing up jQuery and non-jQuery too much. Don't use $(selector)[0].value when $(selector).val() is more appropriate.
2) You're trying to target your elements by their ID when they only have a name. $("#Capital_PA") should be $('[name="Capital_PA"]'), for example.
3) Your .input selector is targeting a class when it should be targeting the input element itself. Like: $('input').
Here's some corrected code
You are trying to find elements like this
$("#ConceptEstimate_GrandTotal")
This means "use jQuery to find an element which has the id of ConceptEstimate_GrandTotal"
When we look at your HTML the only similar element is
<input name="ConceptEstimate_GrandTotal" type="text" />
However this element has a name of ConceptEstimate_GrandTotal, not an id.
Therefore, the result of your $(...) will be just an empty jQuery object (let's call it x),
so x[0] is undefined and you can't do undefined.value, so you'll get an error and everything stops.
This applies to everywhere you try to get an element.
The problem might have been clearer if you kept to vanilla JavaScript document.getElementById(id_attribute_value), as this will give null (falsy) and not an empty object (truthy) when it doesn't find anything
Easiest way to fix it is add the relevant id attributes to your elements
<input name="ConceptEstimate_GrandTotal"
id="ConceptEstimate_GrandTotal"
type="text"
/>
It seems that you need some basics :
<input /> -> $('input')
<input id="whatever" /> -> $('#whatever')
<input class="whatever" /> -> $('.whatever')
<input name="whatever" /> -> $('[name="whatever"]')
I think it might be because the values you get from your form are all Strings.
did you try to parseInt() the values?
For example
$("#Capital_PA")[0].value = parseInt(a) * (parseInt(c)/100) * (parseInt(e)/100)
Can you provide some output or error messages if this is not the case?
In addition you have to add the attribute id to your input fields.
Next Question I have is: why isn't there a "value" attribute provided?
How do you set the values of your input fields?
Related
I have the following:-
$("#c1").val(($("#b1").val() * $("#Doctor.MedicarePatients").val()));
where the result should be 75 * 262 = *** but i got NaN. any advice?
b1 = 75
while
Doctor.MedicarePatients = 362
c1 markup <input type="text" class="form-control" disabled="" id="c1" name="c1" value="272">
b1 markup <input type="text" class="form-control" id="b1" name="b1" value="75">
Doctor.MedicarePatients markup <input type="hidden" class="form-control" id="Doctor_MedicarePatients" name="Doctor.MedicarePatients" value="362">
This issue is happening as $("#Doctor.MedicarePatients").val() is actually returning undefined as we can not have a . in the id selector. You will need to escape dot using \\ to get the actual result.
As mentioned in the docs:
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").
With Error:
console.log($("#Doctor.MedicarePatients").val())
$("#c1").val(($("#b1").val() * $("#Doctor.MedicarePatients").val()));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="b1" value="259" /><input id="Doctor.MedicarePatients" value="118" /><br/>
<input id="c1" value="" />
Without Error:
console.log($("#Doctor\\.MedicarePatients").val())
$("#c1").val(($("#b1").val() * $("#Doctor\\.MedicarePatients").val()));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="b1" value="259" /><input id="Doctor.MedicarePatients" value="118" /><br/>
<input id="c1" value="" />
You can not have . in the selector. In such case read the value as below:
$("#c1").val(($("#b1").val() * $("#Doctor\\.MedicarePatients").val()));
The issue in your code was this snippet $("#Doctor.MedicarePatients").val(), the problem was the id of the input element was Doctor_MedicarePatients, but you were selecting the wrong one with .(Dot), so it return undefined.
So the calculation was happening as undefined * 75 which returned as NaN
See the below updated code.
$("#c1").val($("#b1").val() * $("#Doctor_MedicarePatients").val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" disabled="" id="c1" name="c1" value="272">
<input type="text" class="form-control" id="b1" name="b1" value="75">
<input type="hidden" class="form-control" id="Doctor_MedicarePatients" name="Doctor.MedicarePatients" value="362">
You need to have a fallback option if the value of your input is not a number. You can use parseFloat or parseInt then add " || 0" at the end.
function myFunction() {
var first_number = parseFloat(document.getElementById("first-number").value) || 0;
var second_number = parseFloat(document.getElementById("second-number").value) || 0;
document.getElementById("demo").innerHTML = first_number * second_number;
}
<p id="demo"></p>
<input id="first-number" type="text">
<input id="second-number" type="text">
<button onclick="myFunction()">Calculate</button>
I have a computation fare using the getElementById.innerHTML the total fare showing using <h5 id="totalFare"></h5> but instead if getElementByID i want to parse in getElementsByName by using a <input type="number" name="totalFare" readonly /> i'm searching a lot page to find out the answer, below is my codes. i hope you can help me.
<input type="number" id="adults" min="0" onkeyup="calculate()" name="booking[adults]" class="validate" value="0" required>
<input type="number" id="children" min="0" onkeyup="calculate()" name="booking[children]" class="validate" value="0" required>
<input type="number" id="senior" min="0" onkeyup="calculate()" name="booking[senior]" class="validate" value="0" required>
<script type="text/javascript">
function calculate(){
var adults = document.getElementById("adults").value;
var children = document.getElementById("children").value;
var senior = document.getElementById("senior").value;
var Fare = document.getElementById("hideFare").value;
var values = fare(adults, children, senior, Fare);
console.log(values)
document.getElementById("totalFare").innerHTML = values.totalFare;
}
function fare(x, y, z, a) {
var res = {};
res.totalFare = (( x * a) + (y * (a *.80)) + (z * (a *.80)))
return res
}
</script>
Use getElementsByName like below.
console.log(document.getElementsByName("test")[0].value);
<input type="text" name="test" id="testing" value="This is a value" />
The document.getElementsByName("test") gives you something like an array (called a collection of elements since there could be multiple elements with the same name), so the [0] is there to get the first index which is the value you wanted. Look at the link below for more information.
https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp
H i have a button "Add text" when on-click it creates the text-boxes,now How can i get the count of text-boxes in JavaScript i create text-boxes like
<input type="text" name="my_textbox[1]" id="my_textbox1" />
<input type="text" name="my_textbox[2]" id="my_textbox2" />
<input type="text" name="my_textbox[3]" id="my_textbox3" />
<input type="text" name="my_textbox[4]" id="my_textbox4" />
the reason why i need to count is ,i am fetching values from ajax and creating new text-box appending new text-box like :
<input type="text" name="my_textbox[5]" id="my_textbox5" value="seomthing"/>
Now I would like to know the number of text-boxes present. It would be best if I can get the count through JavaScript .
Thanks in advance.
Give your inputs a classname so you can identify them as a group:
<input class="myInputs" type="text" name="my_textbox[1]" id="my_textbox1" />
Then in your javascript select them with querySelectorAll() and look at the length of the returned collection:
var inputs = document.querySelectorAll('.myInputs')
var number_of_inputs = inputs.length
Use document.querySelectorAll() to get all the elements matching substring of id (https://www.w3.org/TR/selectors/#attribute-substrings). This '[id^="my_textbox"]' syntax means you are selecting all elements with id starting with "my_textbox" string. The just take the length of queried collection and you are done. Please see snippet below:
var textboxCount = document.querySelectorAll('[id^="my_textbox"]').length;
console.log(textboxCount);
<input type="text" name="my_textbox[1]" id="my_textbox1" />
<input type="text" name="my_textbox[2]" id="my_textbox2" />
<input type="text" name="my_textbox[3]" id="my_textbox3" />
<input type="text" name="my_textbox[4]" id="my_textbox4" />
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();
}
I literally started trying to teach myself javascript less than 48 hours ago. Outside of just wanting to learn it I also have a small personal project I'm working on and using as sort of my working learn as I go example. But I've hit a problem, which I'm sure is rather basic, I'm just hampered by lack of much javascript knowledge.
Basically it is just an averaging problem.
There are going to be 4 inputs fields with the 4th being a rounded to the nearest whole number average of the first three fields.
This 4 field configuration is going to get used multiple times on the page.
I want it to work in "real time" and not with a calculate button so I'm assuming "onKeyup" is needed. (no validation of any kind is needed or submit or saving or anything)
The only code I've been able to get close is really really ugly, long, and convoluted. I can't help but think there is a very simple way to do it and just get the same function to apply to each grouping of inputs. It will look like below but probably much longer.
some text
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
some text
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
Thanks in advance. This is part of a larger problem but I've tried to strip it down to it's essence and seeing it work and understanding it will go a long way to helping me solve some other problems.
To start with use a different markup, there should only be a single id per page, so use classes, it make it easier to target everything too. Also if the effect is to use the last input as a display you can use readonly instead of disabled
<p>some text</p>
<div class="group">
<input class="a" type="number" /><br/>
<input class="b" type="number" /><br/>
<input class="c" type="number" /><br/>
<input class="final" value="0" readonly />
</div>
<p>some text</p>
<div class="group">
<input class="a" type="number" /><br/>
<input class="b" type="number" /><br/>
<input class="c" type="number" /><br/>
<input class="final" value="0" readonly />
</div>
Here is an example done in jquery
$(function() {
$('.group input').on('click', function() {
var count = parseInt($(this).val()) || 0;
$(this).siblings(':not(.final)').each(function() {
if ($(this).val()) count = count + parseInt($(this).val());
});
$(this).siblings('.final').eq(0).val(count);
});
});
And the demo is here: http://jsfiddle.net/4S4Vp/1/
This should be understandable for your level. The second set of inputs will be named a-2 with calc(2) and so on.
<input id="a-1" type="number" onkeyup="calc(1)" value="0" /><br/>
<input id="b-1" type="number" onkeyup="calc(1)" value="0" /><br/>
<input id="c-1" type="number" onkeyup="calc(1)" value="0" /><br/>
<input id="final-1" value="0" disabled />
function calc( n ) {
var a = document.getElementById("a-" + n ).value;
var b = document.getElementById("b-" + n ).value;
var c = document.getElementById("c-" + n ).value;
document.getElementById("final-" + n ).value = Math.round((parseInt(a)+parseInt(b)+parseInt(c))/3);
}
This is really quick and dirty, but if you know how many inputs you have, this should work:
// these would instead be your textboxes
var a = document.getElementById('a').value();
var b = document.getElementById('b').value();
var c = document.getElementById('c').value();
var avg = (a+b+b)/3;
document.getElementById('c').value() = avg;
Here is a jsfiddle so you can play with the idea and see if it works as you want it to.
Use jquery.
see the live demo on jsfiddle
some text
<div id="div1">
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
</div>
some text
<div id="div2">
<input id="a" type="number" /><br/>
<input id="b" type="number" /><br/>
<input id="c" type="number" /><br/>
<input id="final" value="0" disabled />
</div>
<script type="text/javascript">
$("#div1 input").bind('change keyup click',function(){
var final = 0;
$("#div1 input").not("#div1 #final").each(function(idx,el){
final += (el.value) ? parseInt(el.value) : 0;
});
$("#div1 #final").val(final/3);
});
$("#div2 input").bind('change keyup click',function(){
var final = 0;
$("#div2 input").not("#div2 #final").each(function(idx,el){
final += (el.value) ? parseInt(el.value) : 0;
});
$("#div2 #final").val(final/3);
});
</script>
I hoped to flag this as duplicate, but because this answer does not have code, enjoy:
// find all inputs in the page and gather data trying to convert it to number
var data = [].map.call( document.querySelectorAll('input'), function (v) {
if (typeof v.value * 1 === 'NaN') {
return 'NaN';
}
return v.value * 1;
});
// not all data will be valid, so we filter it
data = data.filter( function (v) {
return !isNaN(v);
});
// and then calculate average
var avg = data.reduce( function (v, v1) {
return v + v1;
}) / data.length;