getElementsByName instead of getElementById - javascript

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

Related

calculate two input field values in javascript

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();
}

Javascript Multiply Function Not Working

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?

Simple Gallon Calculator

I'm attempting to build a simple web form that takes 3 number inputs and outputs one number based on this formula: (a*b*c)/271).
This is the code I have but nothing is displayed in the output.
Clearly I have almost no clue what I'm doing.
I appreciate all help:
<body>
<img id="logo"src="images/a&l.png" alt="A&L Cesspool"/>
<h1>Grease Trap Gallon Calculator<h2>
<form name=calculator">
<input label="length" type="number" id="a">
<input label="width" type="number" id="b">
<input label="height" type="number" id="c">
<input type=Button value=Calculate onClick="gallons();">
<input name="OUTPUT" id="output" SIZE="4" maxlength="6" >
</form>
<script language="JavaScript" type="text/javascript">
<!--
function gallons() {
var LENGTH = document.calculator.a.value;
var WIDTH = document.calculator.b.value;
var HEIGHT = document.calculator.c.value;
var Total =(LENGTH*WIDTH*HEIGHT)/271;
document.calculator.OUTPUT.value = Total;
}
// -->
</script>
document.forms.calculator. There's no such thing as document.calculator. Also, form elements need name attributes to refer to them in form context, not IDs.
In other news
You have unclosed quotes
You have irregular naming conventions (OUTPUT, a, Total)
You have irregular quotes policy (sometimes you have, sometimes you don't).
So basically
<form name="calculator">
<input label="length" type="number" name="a">
<input label="width" type="number" name="b">
<input label="height" type="number" name="c">
<input type=Button value=Calculate onClick="gallons();">
<input name="OUTPUT" id="output" SIZE="4" maxlength="6">
</form>
function gallons() {
var LENGTH = document.forms.calculator.a.value;
var WIDTH = document.forms.calculator.b.value;
var HEIGHT = document.forms.calculator.c.value;
var Total = (LENGTH * WIDTH * HEIGHT) / 271;
document.forms.calculator.OUTPUT.value = Total;
}
Please grab a proper tutorial from MDN or some similar good source, and start reading.
Your call to document.calculator is not finding the element because its looking by id
change your form definition and it will work
<form name="calculator" id="calculator">

Simple reusable javascript averaging function for multiple forms on same page

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;

javascript (math) adding up an array

I have two javascript text boxes.
<input type="text" name="test" value="300" />
<input type="text" name="test" value="500" />
How can I use javascript to alert the total price of the items in the text box?
Would something like this work?
var price = document.getElementById("test");
alert(price)
This will take all input elements into account (useful if you have many). Filter them by type and get their values in loop:
var inputs = document.getElementsByTagName("input");
var total = 0;
for (var i = 0; i < inputs.length; i++){
if (inputs[i].type = "text"){
total += parseInt(inputs[i].value, 10);
}
}
alert(total);
<input id="test1" type="text" name="test" value="300" />
<input id="test2" type="text" name="test" value="500" />
JS:
var price = parseInt(document.getElementById("test1").value, 10) + parseInt(document.getElementById("test2").value, 10);
<input id="price1" type="text" name="test" value="300" />
<input id="price2" type="text" name="test" value="500" />
This will work:
var price = document.getElementById("price1").value+document.getElementById("price2").value;
alert(price)
Note Do not have other tags with id="price1" or id="price2"
What you have written will not work, for several reasons. Firstly, as the name suggests, getElementById gets an element based on the value of the id attribute. You haven't given your input elements an id attribute, so that's not going to work.
Secondly, document.getElementById('someId') returns an element, but you want the value. You can use the value property to get it:
var price1 = parseInt(document.getElementById("test1").value, 10);
var price2 = parseInt(document.getElementById("test2").value, 10);
alert(price1 + price2);
This will work with the following HTML:
<input type="text" name="test" id="test1" value="300" />
<input type="text" name="test" id="test2" value="500" />
Note the use of parseInt. The value property returns a String, so we use parseInt to attempt to parse that into a Number. If you don't use it, price1 + price2 will simply concatenate the strings.

Categories