Adding input fields together and displaying in a label - javascript

I'm writing a program to add tests, exams, practicals, assignments to a module.
With regards to the course weighting I was wondering if you could dynamically change the value of the total weighting when a user enters a weighting per task.
Like this:
Problem
The inputs in the red rectangle should be added up and displayed in the blue rectangles label.
In turn, the blue rectangle should be added up and displayed in the green rectangles label.
Any help will be appreciated please
I have tried this so far:
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="fnum" size="35" id="first">
+ Second Number:
<input type="text" name="snum" size="35" id="sec">
+ Third Number:
<input type="text" name="lom" size="35" id="third3">
<br>
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<button type="button" onclick="Calculate();">Calculate</button>
<script lang="javascript">
function Calculate() {
var first = document.getElementById('first').value;
if(document.getElementById('sec'))
{
var last = document.getElementById('sec').value;
}
else
{
var last = 0;
}
if(document.getElementById('third'))
{
var third = document.getElementById('third').value;
}
else
{
var third = 0;
}
document.getElementById('ans').value = parseInt(first) + parseInt(last) + parseInt(third);
document.form1.submit();
}
https://jsfiddle.net/www1fxjb/9/
What I am asking is to change the label as soon as the numbers change in the input fields.

You need to use the onchangeevent in your input fields properties.
You can then point your onchangeevent to your calculate method.
Also, add default values of "0" in your input fields so that it will always have a value to add and this will prevent errors.
<input type="number" name="fnum" size="35" id="first" onchange="Calculate();" value="0"/>
+ Second Number:
<input type="number" name="snum" size="35" id="second" onchange="Calculate();" value="0"/>
+ Third Number:
<input type="number" name="lom" size="35" id="third" onchange="Calculate();" value="0"/>
<br />
Answer:
<input type="text" name="ans" size="35" id="ans" />
Javascript:
<script lang="javascript">
function Calculate() {
if (document.getElementById('first')) {
var first = document.getElementById('first').value;
}
else {
var first = 0;
}
if (document.getElementById('second'))
{
var second = document.getElementById('second').value;
}
else
{
var second = 0;
}
if (document.getElementById('third'))
{
var third = document.getElementById('third').value;
}
else
{
var third = 0;
}
document.getElementById('ans').value = parseInt(first) + parseInt(second) + parseInt(third);
document.form1.submit();
}
</script>
Hope it helps.

Related

How can I get the values of multiple textboxes and store them in a variable

I'm trying to create a page that calculates all your hours worked. However, I can't get it to output anything. I've tried to use querySelectorAll and getElementsByTagName (by changing the class tag to name in the textbox's).
But when I execute I get "undefined" instead of numbers.
Can someone explain what I'm doing wrong?
function calcHours() {
let hoursWorked = parseInt(document.querySelectorAll(".txtBox1").value);
const hoursWorkedText = "Hours worked: "
if (Number.isNaN(hoursWorked)) {
//code to throw error.
errorCalc("value is not a number");
}
else {
//code to run normally.
document.getElementById('hoursTotal').innerHTML = hoursWorked;
document.getElementById('hrWorkTxt').innerHTML = hoursWorkedText;
}
}
function errorCalc(errorTxt) {
alert("You done goofed, " + errorTxt + " error");
}
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<p id="hrWorkTxt">
<p id="hoursTotal">
<input type="button" value="Calculate" onclick="calcHours()">
Couple initial notes:
There is no type textbox for inputs. You probably mean text. Since you want to calculate numbers i think you should use the type number. This way you can skip checking if the input is NAN etc...
Since you dealing with more than one input, in order to get all values you should first iterate all of them and then get each value.
Anyway i think this is what you trying to do:
function calcHours() {
let hoursWorked = document.querySelectorAll(".txtBox1");
let hoursWorkedTotal =0;
for (let i = 0; i < hoursWorked.length; i+=1) {
hoursWorkedTotal += parseInt(hoursWorked[i].value);
}
document.getElementById('hoursTotal').innerHTML = hoursWorkedTotal;
}
<input type="number" class="txtBox1" value="0" />
<input type="number" class="txtBox1" value="0" />
<input type="number" class="txtBox1" value="0" />
<input type="number" class="txtBox1" value="0" />
<input type="number" class="txtBox1" value="0" />
<input type="number" class="txtBox1" value="0" />
<input type="number" class="txtBox1" value="0" />
<button type="button" onclick="calcHours()">Calculate</button>
<p id="hoursTotal"></p>
Instead of accessing the p element with .innerHTML, try .value.
The document.querySelectorAll(".txtBox1") instruction returns an array of elements so it is not possible to access to .value property in the way you are trying.
You should iterate the element of the returning array in this way:
var elements = document.querySelectorAll(".txtBox1");
for (var i = 0; i < elements.length; i++) {
// do something with elements[i]
}
document.querySelectorAll(".txtBox1") returns an object so you have to get the data from it.
I think the following code will work for you.
function calcHours() {
let hoursWorked = document.querySelectorAll(".txtBox1");
let hoursWorkedTotal =0;
for (var i=0; i<hoursWorked.length; i++){
//console.log(hoursWorked[i].value);
hoursWorkedTotal += parseInt(hoursWorked[i].value);
}
const hoursWorkedText = "Hours worked: "
if (Number.isNaN(hoursWorked)) {
//code to throw error.
errorCalc("value is not a number");
}
else {
//code to run normally.
document.getElementById('hoursTotal').innerHTML = hoursWorkedTotal;
document.getElementById('hrWorkTxt').innerHTML = hoursWorkedText;
}
}
function errorCalc(errorTxt) {
alert("You done goofed, " + errorTxt + " error");
}
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<input type="textbox" class="txtBox1">
<p id="hrWorkTxt">
<p id="hoursTotal">
<input type="button" value="Calculate" onclick="calcHours()">

How to display recommendations after calculating a certain result?

How do I display something like a recommendation list after a user calculate a result from the inputs? E.g having the user to key in the salaries of the family and calculating the PCI (Per capita income) and after they key in and press on the calculate button which then will trigger a list of recommendations based on the amount of PCI the family have (Maybe tables that shows different results based on different categories of PCI?)
<!DOCTYPE html>
<html>
<head>
<script src="common.js"></script>
<script>
function cal()
{
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var total = (parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
document.getElementById('total').value = total;
alert (total);
}
</script>
</head>
<body>
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" value="" placeholder="Enter your 4th family income..."/>
<input id="members" value="" placeholder="Enter the total number of family members..."/>
<br>
<button onclick="cal()"> Calculate PCI!</button>
<br>
Total: <input id="total"> </input>
</body>
</html>
You can create a hidden div that holds the data then show that div when user clicks the button
HTML:
<div id="divToShow" style="display:none;" class="table_list" >
//put your data table here
</div>
<input type="button" name="myButton" value="Show Div" onclick="showDiv()" />
Javascript:
function showDiv() {
document.getElementById('divToShow').style.display = "block";
}
This should get you there: Jsfiddle.
<form id="form">
<input id="number1" type="number" min="1" name="number" placholder="add value one"> +
<input id="number2" type="number" min="1" name="number" placholder="add value one">
<button>Submit</button>
</form>
var form = document.getElementById('form');
number1 = document.getElementById('number1');
number2 = document.getElementById('number2');
form.onsubmit = function() {
var total = +number1.value + +number2.value; // add + before
alert( total );
};
function cal(){
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var recommanted;
var recommandations=[
{maxpci:1000,recommandation:'first_recommandation'},
{maxpci:2000,recommandation:'second_recommandation'},
{maxpci:3000,recommandation:'third_recommandation'},
{maxpci:6000,recommandation:'fourth_recommandation'}
];
var total=(parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
if(recommandations[recommandations.length - 1].maxpci < total ){recommanted=recommandations[recommandations.length - 1].recommandation;}
else{
for (var i = 0; i < recommandations.length; i++) {
if(total <= recommandations[i].maxpci){
recommanted=recommandations[i].recommandation;break;}
}}
document.getElementById('result').innerHTML = "Your PCI : "+total+"</br>Recommandation : "+recommanted;
}
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" type="number" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" type="number" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" type="number" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" type="number" value="" placeholder="Enter your 4th family income..."/>
<input id="members" type="number" value="" placeholder="Enter the total number of family members..."/>
</br>
<button onclick="cal()"> Calculate PCI!</button>
</br>
<div id="result">
</div>

How to set paragraph to textbox text

Let us say I have an HTML form, with two textboxes, I want to add the two numbers in the two textboxes and display the result in a paragraph. How can I do that?
Change paragraph according to textbox is what I can't find!
Very simple:
document.getElementById('sum').onsubmit = add;
function add(e) {
e.preventDefault();
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var result = 'Result: ' + String(parseInt(num1) + parseInt(num2));
var p = document.getElementById('result');
p.innerHTML = result;
}
<form id="sum">
<label for="num1">First number:</label>
<br />
<input type="text" id="num1" />
<br />
<label for="num1">Second number:</label>
<br />
<input type="text" id="num2" />
<br />
<input type="submit" value="Add" />
</form>
<p id="result">Result:</p>
In the html we have a form with 3 inputs, 2 are type text and one is type submit. and also a paragraph.
In the javascript we assign to the form's onsumbit event the function add(), in the function we prevent the default so the form wont refresh the page, then we get the 2 values that were inputed, create a string that would contain the sum of those values and set the paragraph's innerHTML to it.
Create a calculator function and then you can fire it on keyup or you can assign it to a button if you'd like.
function calcTotal(){
var inputs = document.getElementsByTagName('input'),
result = 0;
for(var i=0;i<inputs.length;i++){
if(parseInt(inputs[i].value))
result += parseInt(inputs[i].value);
}
document.getElementById('total').innerHTML = 'Total: ' + result;
}
<form>
<input onkeyup="calcTotal()" type="text" />
<input onkeyup="calcTotal()" type="text" />
</form>
<p id="total"></p>
follow bellow JS code:
<html>
<head>
<title>Sum Two Number</title>
<script language="javascript">
function addNumbers()
{
var val1 = parseInt(document.getElementById("value1").value);
var val2 = parseInt(document.getElementById("value2").value);
if(val1 !== "" && val2 !== "") {
var result = val1 + val2;
document.getElementById('result').innerHTML = result;
}
}
</script>
</head>
<body>
value1 = <input type="text" id="value1" name="value1" value="0" onkeyup="javascript:addNumbers()"/>
value2 = <input type="text" id="value2" name="value2" value="0" onkeyup="javascript:addNumbers()"/>
<p>Answer = <span id="result"></span></p>
</body>
</html>
In this example, you have a form with 2 input. When you press on a button, the value of those 2 input is added inside a paragraph.
Hope this help.
function addInputContentToParagraph() {
var txtValue1 = document.getElementById('textbox1').value;
var txtValue2 = document.getElementById('textbox2').value;
document.getElementById('para').innerHTML = txtValue1 + ' ' + txtValue2;
}
a {
cursor:pointer;
border:1px solid #333;
padding:4px;
margin:10px;
display:inline-block;
}
<form id="myForm" name="myForm">
<input type="text" name="textbox1" id="textbox1" value="1">
<input type="text" name="textbox2" id="textbox2" value="2">
</form>
<a onclick="addInputContentToParagraph();">Add Input Values to Paragraph</a>
<p id="para"></p>

Trying to make a form that adds number automatically without submit like event listner

Please help I have done this so far. I want all 6 fiels working how can i do this? This is basically to calculate exam result so as fast help needed.
function myFunction() {
var a = parseFloat(document.getElementById("txt1").value);
var b = parseFloat(document.getElementById("txt2").value);
var c = parseFloat(document.getElementById("txt3").value);
var d = parseFloat(document.getElementById("txt3").value);
var e = parseFloat(document.getElementById("txt4").value);
var f = parseFloat(document.getElementById("txt5").value);
var g = parseFloat(document.getElementById("txt6").value);
var g = a + b + c + d + e + f + g;
// If x = NaN empty variable x
if (!g) {
x = '';
}
document.getElementById("demo").innerHTML = x;
}
window.onload = function() {
var inputs = document.getElementsByClassName('calc');
for (var i = 0; i < inputs.length; i++) {
// Listen for input > Call MyFunction
inputs[i].addEventListener('input', myFunction, false);
}
};
Enter first number:
<input type="text" class="calc" id="txt1" name="text1">Enter second number:
<input type="text" class="calc" id="txt2" name="text2">Enter third numve
<input type="text" class="calc" id="txt3" name="text3">Enter fourth number:
<input type="text" class="calc" id="txt4" name="text4">Enter fifth number:
<input type="text" class="calc" id="txt5" name="text5">Enter sixth number:
<input type="text" class="calc" id="txt6" name="text6">
<p id="demo"></p>
Since you have more inputs and you have expanded on my previous answer can cut down on the source code by using getElementsByClassName() and a for loop to add up the inputs.
Don't forget to close your inputs using />. I have also removed the ID's as the class name and for loop will take care of targeting those elements.
function myFunction() {
var a=0;
var Calc=document.getElementsByClassName('calc');
for(var i=0; i<Calc.length; i++){
if(parseFloat(Calc[i].value)){
a=a+parseFloat(Calc[i].value);
}
}
// If a = NaN empty variable a
if(isNaN(parseFloat(a))){x='';}
// Changed from .innerHTML to .value
document.getElementById("Result").value = a;
}
window.onload=function(){
var inputs=document.getElementsByClassName('calc');
for(var i=0; i<inputs.length; i++){
// Listen for input > Call MyFunction
inputs[i].addEventListener('input',myFunction,false);
}
};
Enter first number: <input type="text" class="calc"/>
Enter second number:<input type="text" class="calc">
Enter third numve <input type="text" class="calc"/>
Enter fourth number:<input type="text" class="calc"/>
Enter fifth number: <input type="text" class="calc"/>
Enter sixth number:<input type="text" class="calc"/>
<!-- Div Removed and input added -->
<input type="text" id="Result"/>
Request Edit: Change div element to input for results
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
function myFunction() {
Thanks NewTo Js for helping me This is working :)
var a=0;
var Calc=document.getElementsByClassName('calc');
for(var i=0; i<Calc.length; i++){
if(parseFloat(Calc[i].value)){
a=a+parseFloat(Calc[i].value);
}
}
// If x = NaN empty variable x
if(!a){a='';}
document.getElementById("demo").innerHTML = a;
}
window.onload=function(){
var inputs=document.getElementsByClassName('calc');
for(var i=0; i<inputs.length; i++){
// Listen for input > Call MyFunction
inputs[i].addEventListener('input',myFunction,false);
}
};
Enter first number: <input type="text" class="calc" id="txt1" name="text1">
Enter second number:<input type="text" class="calc" id="txt2" name="text2">
Enter third numve <input type="text" class="calc" id="txt3" name="text3">
Enter fourth number:<input type="text" class="calc" id="txt4" name="text4">
Enter fifth number: <input type="text" class="calc" id="txt5" name="text5">
Enter sixth number:<input type="text" class="calc" id="txt6" name="text6">
<p id="demo"></p>

can not add two multiplications result in text box in html

sir
i have 7 text boxes .1st two take values from user and display the multiplication result on 3rd text box when it clicked.4th and 5th textboxes also take values and display the multiplication result in 6th text box when it clicked.now 7th textbox will display the addition result when it clicked.7th textbox takes the values from 3rd and 6th textbox.
my problem is that i can not do the addition and cant display the result in 7th text box in html and jscript.plz help me.....i am attached the code...
<html>
<script>
function getText1(){
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var tot1=parseInt(in1)*parseInt(in2);
document.getElementById('tot1').value=tot1;
}
function getText2(){
var in1=document.getElementById('in3').value;
var in2=document.getElementById('in4').value;
var tot2=parseInt(in1)*parseInt(in2);
document.getElementById('tot2').value=tot2;
}
function gt1(){
var in1=document.getElementById('tot1').value;
var in2=document.getElementById('tot2').value;
var gt1=parseInt(in1)+parseInt(in2);
document.getElementById('gt').value = gt1;
</script>
<form>
<input type="text"id="in1"/>
<input type="text" id="in2"/>
<input type="text" onclick="getText1()" id="tot1"/>
<br>
<input type="text"id="in3"/>
<input type="text" id="in4"/>
<input type="text" onclick="getText2()" id="tot2"/>
<br>
<input type="text" onclick="gt1()" id="gt1"/>
</form>
</html>
<html>
<script>
function getText1(){
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var tot1=parseInt(in1)*parseInt(in2);
document.getElementById('tot1').value=tot1;
}
function getText2(){
var in1=document.getElementById('in3').value;
var in2=document.getElementById('in4').value;
var tot2=parseInt(in1)*parseInt(in2);
document.getElementById('tot2').value=tot2;
}
function gt(){
var in1=document.getElementById('tot1').value;
var in2=document.getElementById('tot2').value;
var gt1=parseInt(in1)+parseInt(in2);
document.getElementById('gt1').value = gt1;
}
</script>
<form>
<input type="text"id="in1"/>
<input type="text" id="in2"/>
<input type="text" onclick="getText1()" id="tot1"/>
<br>
<input type="text"id="in3"/>
<input type="text" id="in4"/>
<input type="text" onclick="getText2()" id="tot2"/>
<br>
<input type="text" onclick="gt()" id="gt1"/>
</form>
</html>
use this code it is working. and compare with own code. thanks..
There are several problem
1). Element id is one line is incorrect. It should be:
document.getElementById('gt1').value = gt1;
2). result variable is undefined. It should be:
if (!isNaN(gt1))
3). onclick="gt1()" will not work (because there is id with the same name gt1). Use, for example:
function getText3() { ... }
and
<input type="text" onclick="getText3()" id="gt1"/>
Fiddle.
Update. Ok, I didn't notice that you want multiplication, but somewhy had written + in getText1() and getText2() functions. Then you should also replace these two + with *:
Multiplication fiddle.
You dont have element with id 'gt'.
Change last line of code to this:
document.getElementById('gt1').value = gt1;
You have not defined 'result' variable
and in 'gt1()' :
document.getElementById('gt').value = gt1;
1- There is no 'gt' element in the page
2- 'gt1' should renamed to 'result'
and at the end code will be:
<script language="javascript" type="text/javascript">
function getText1() {
var in1 = document.getElementById('in1').value;
var in2 = document.getElementById('in2').value;
var tot1 = parseInt(in1) + parseInt(in2);
document.getElementById('tot1').value = tot1;
}
function getText2() {
var in1 = document.getElementById('in3').value;
var in2 = document.getElementById('in4').value;
var tot2 = parseInt(in1) + parseInt(in2);
document.getElementById('tot2').value = tot2;
}
function gt1() {
var in1 = document.getElementById('tot1').value;
var in2 = document.getElementById('tot2').value;
var result = parseInt(in1) + parseInt(in2);
if (!isNaN(result)) {
document.getElementById('gt1').value = result;
}
//document.getElementById('gt1').value=gt1;
}
</script>
this is work properly.
Check the below code.
<script >
function getext3(){
txt1 = document.getElementById("text1").value;
txt2 = document.getElementById("text2").value;
document.getElementById("text3").value = parseInt(txt1)*parseInt(txt2);
}
function getext6(){
txt1 = document.getElementById("text4").value;
txt2 = document.getElementById("text5").value;
document.getElementById("text6").value = parseInt(txt1)*parseInt(txt2);
}
function getext7(){
txt1 = document.getElementById("text3").value;
txt2 = document.getElementById("text6").value;
document.getElementById("text7").value = parseInt(txt1)+parseInt(txt2);
}
</script>
Text1 : <input type="text" id="text1" value="5"> <br/>
Text2 : <input type="text" id="text2" value="2"> <br/>
Text3 : <input type="text" id="text3" value="" onclick="getext3()"> <br/>
Text4 : <input type="text" id="text4" value="7"> <br/>
Text5 : <input type="text" id="text5" value="10"> <br/>
Text6 : <input type="text" id="text6" value="" onclick="getext6()"> <br/>
Text7 : <input type="text" id="text7" value="" onclick="getext7()"> <br/>

Categories