how to calculate two html txt boxes using javascript - javascript

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>

Related

How to grab ID of multiple input field and sum them in a span as total

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 have two radio button but the the form only can get one radio value even we choose different radio

I want to get the value from radio button that we have choose then multiple with the number in grossSalary. The result will be display on a textbox called epf. There are an error happening, the form only get 0.09 value even we choose 11% radio button.
Here is my javascript
<script>
function get(percent)
{
var percent = document.getElementById('percent').value;
var grossSalary= document.getElementById('grossSalary').value;
var epf = parseFloat(percent)*parseFloat(grossSalary);
epf = epf.toFixed(2);
document.getElementById('epf').value = epf;
}
</script>
Here is my form coding:
<div class="form-group">
<label>Gross Salary</label>
<input type="text" class="form-control" id="grossSalary" name="gross_salary">
</div>
<div class="form-group">
<label>EPF</label>
<input type="radio" id="percent" name="percent" value="0.09" onclick="get(this.value)">9%
<input type="radio" id="percent" name="percent" value="0.11" onclick="get(this.value)">11%
<input type="text" id ="epf" class="form-control" name="epf" >
</div>
</form>
You could use the name instead of the id (because id has to be unique). Also, with jQuery, you could use the change event.
i.e. :
HTML :
<div class="form-group">
<label>Gross Salary</label>
<input type="text" class="form-control" id="grossSalary" name="gross_salary">
</div>
<div class="form-group">
<label>EPF</label>
<input type="radio" name="percent" value="0.09">9%
<input type="radio" name="percent" value="0.11">11%
<input type="text" id ="epf" class="form-control" name="epf" >
</div>
JS :
$("input[name=percent]").change(function() {
var percent = $(this).val();
var grossSalary= $("#grossSalary").val();
var epf = parseFloat(percent)*parseFloat(grossSalary);
$("#epf").val(epf.toFixed(2));
});
Here is the working example on JSFiddle.
Hope it helps.
EDIT Don't forget to include jQuery source in your html file :
One file template :
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="form-group">
<label>Gross Salary</label>
<input type="text" class="form-control" id="grossSalary" name="gross_salary">
</div>
<div class="form-group">
<label>EPF</label>
<input type="radio" name="percent" value="0.09">9%
<input type="radio" name="percent" value="0.11">11%
<input type="text" id ="epf" class="form-control" name="epf" >
</div>
<script>
$("input[name=percent]").change(function() {
var percent = $(this).val();
var grossSalary= $("#grossSalary").val();
var epf = parseFloat(percent)*parseFloat(grossSalary);
$("#epf").val(epf.toFixed(2));
});
</script>
When you are using JS or Jquery than always remember one key point that:
id: used for single selection
class: used for multiple selection
In your case you are using same id for different tags, in that case it returns the first matching html value.
So to get rid of this, you have to use class and iterate over them and get the values.

change the value of a label with using a form but without refresh the page

I would like to create a form that based on the input values, calculation results and enter it in a div / label / bit somewhere in the web page html.
an working similar to that of the currency converters online
(insert the number for the first currency and you can see the result without the page refresh, with use of the submit button or not)
this is a little piece of my code (I can not understand the concept/mechanism to do what I want as described above)
<form id="form" class="green" method="post">
<label class="title">
<span class="titolo-riga required">Number1</span>
<input id="firstId" class="small" type="number" name="number1" required="required" value="0" />
</label>
<label class="title">
<span class="titolo-riga required">Number2</span>
<input id="secondID" class="small" type="number" name="number2" required="required" value="0" />
</label>
<div class="submit"><input type="submit" onclick="return submitForm();" value="Submit"/></div>
</form>
<div><label id="printHere" class="result"></label></div>
this a basic script inside the html:
function submitForm(){
var a = parseInt($("#firstId").val());
var b = parseInt($("#secondID").val());
result = a+ b;
try this simple script with html:
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Add it</button>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">
<br/>Enter second number:
<input type="text" id="txt2" name="text2">
<p id="demo"></p>
<script>
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = +y + +z;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
If I understood it correctly, you are trying to retrieve to input values, do some mathematical operations with them, and return it to the page without refreshing it, if it's so:
make a change event listener on both of inputs, in that case:
$("#firstId").change(function() {
$("#thirdId").val(calculate());
});
$("#secondID").change(function() {
$("#thirdId").val(calculate());
});
make a calculation function:
function calculate() {
var a = parseInt($("#firstId").val());
var b = parseInt($("#secondID").val());
return a+ b;
}
Good Day Sir,
I would suggest you could bind this input value a few different ways to update it on the page, without requiring a refresh. The jQuery library is probably the easiest to implement over straight javascript. Are you familiar with the following functions?
Keyup/Blur?
I created this fiddle for you. Hopefully it helps.
https://jsfiddle.net/wkdjwzfv/
<script>
$(function(){
//val for firstid
$("#firstId").keyup(function() {
//val of firstId
var total = parseInt($(this).val()) + parseInt($("#secondID").val());
console.log(total);
$("#total").empty().append(total);
});
//for keyup for second
$("#secondID").keyup(function() {
var total = parseInt($(this).val()) + parseInt($("#firstId").val());
console.log(total);
$("#total").empty().append(total);
});
})
</script>
Try this html and jquery combination:
<form id="form" class="green">
<div class="element-number column1">
<label for="avanti-testa" class="title">
<span class="titolo-riga required">Number1</span>
<input id="firstId" class="small" type="number" min="0" max="100" name="number1" required="required" value="0" />
</label>
</div>
<div class="element-number column1">
<label for="avanti-testa" class="title">
<span class="titolo-riga required">Number2</span>
<input id="secondID" class="small" type="number" min="0" max="100" name="number1" required="required" value="0" />
</label>
</div>
<div id="answer"></div>
<button id="submitForm" type="button">Submit</button>
</form>
<script>
// assuming jQuery is loaded
(function($) {
$('#submitForm').on('click', function (e) {
e.preventDefault();
var answer = parseInt($('#firstId').val(), 10) + parseInt($('#secondId').val(), 10);
$('#answer').text(answer);
});
})(jQuery);
</script>
As an alternative solution I'd like to post a simplistic answer created with AngularJS. Here is the Plunker: http://plnkr.co/edit/46Xf23jUhrmaT2x31S0K?p=preview
The code would be:
<div class="col-md-2 col-md-offset-5 form-group">
<input class="form-control" type="number" ng-model="firstValue" />
<p class="text-center">+</p>
<input class="form-control" type="number" ng-model="secondValue" />
</div>
<div class="panel panel-primary col-md-2 col-md-offset-5 text-center">
{{ firstValue + secondValue }}
</div>
The classes are from Bootstrap, just for making it little bit nicer.

JavaScript Word Count - Calculation

I have a script to count the words in an attachment which works fine.
function loadDemo() {
WordCount.words("file_attach", function(words) {
document.getElementById("words").innerText = words;
});
var elt = document.getElementById("words");
var words = elt.options[elt.selectedIndex].value;
words = parseInt(words);
var tprice = (words /500) * 12;
document.getElementById("tprice").innerText=tprice;
}
I then wanted to calulate a price which is printed in span box below.
The word count is printed to its span, but price is not. Where have i gone wrong in my calculation?
<div id="result"></div>
<label for="name"><span>Name</span>
<input type="text" name="name" id="name" placeholder="Enter Your Name" />
</label>
<label for="email"><span>Email Address</span>
<input type="email" name="email" id="email" placeholder="Enter Your Email" />
</label>
<label for="file"><span>Attachment</span>
<input type="file" name="file_attach" id="file_attach" onChange="loadDemo()" />
</label>
<label for="words"><span>No. of Words</span>
<span id="words"></span>
</label>
<label for="tprice"><span>Price</span>
<span id="tprice"></span>
</label>
<label for="message"><span>Message</span>
<textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
</label>
<label><span> </span>
<button class="submit_btn" id="submit_btn">Submit</button>
</label>
Above is HTML of form.
Thanks
Your JavaScript for looking up the words is:
var elt = document.getElementById("words");
var words = elt.options[elt.selectedIndex].value;
but the second line is what you'd use for retrieving values from a select dropdown. The element <span id="words"></span> however is not a select element. You need to use:
var elt = document.getElementById("words");
var words = elt.textContent;
Demo
As a side note, it's a bit unusual to use <label> tags for things that aren't form controls. Specifically there's no point in using the label's for attribute to point to a non-input element because they can't receive focus.

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">

Categories