I'm trying to add my getExamGrades and getLabGrades together by calling my other function to get a total grade but nothing I've tried works. Everything I've done so far just eliminates both of the functions I call and leaves everything blank. The code below works perfectly fine, just need help with the last part and then I can figure out the other variables and functions.
<!DOCTYPE html>
<html>
<header>
<script>
function getExamGrades()
{
var exam1 = document.getElementById("Exam1").value;
var exam2 = document.getElementById("Exam2").value;
var exam3 = document.getElementById("Exam3").value;
var Exams = Number(exam1) + Number(exam2) + Number(exam3);
document.getElementById("examGrade").innerHTML = Exams;
}
function getLabGrades()
{
var lab1 = document.getElementById("Lab1").value;
var lab2 = document.getElementById("Lab2").value;
var lab3 = document.getElementById("Lab3").value;
var Labs = Number(lab1) + Number(lab2) + Number(lab3);
document.getElementById("labGrade").innerHTML = Labs;
}
function getTotalGrades()
{
//var Total = Number(getExamGrades()) + Number(getLabGrades();
document.getElementByID("totalGrade").innerHTML = Total;
}
</script>
</header>
<body>
Exam1: <input type = "text" name="Exam1" value ="100" id="Exam1">
Exam2: <input type = "text" name="Exam2" value ="100" id="Exam2">
Exam3: <input type = "text" name="Exam3" value ="100" id="Exam3">
<br><br>
<button onClick="getExamGrades()"> Calculate Exam Grade </button>
Total: <output id="examGrade"> </output>
<br><br>
Lab1: <input type = "text" name="Lab1" value ="100" id="Lab1">
Lab2: <input type = "text" name="Lab2" value ="100" id="Lab2">
Lab3: <input type = "text" name="Lab3" value ="100" id="Lab3">
<br><br>
<button onClick="getLabGrades()"> Calculate Lab Grade </button>
Total: <output id="labGrade"> </output>
<br><br>
<button onClick="getTotalGrades()"> Calculate Total Grade </button>
Final Grade: <output id="totalGrade"> </output>
</body>
</html>
Your functions are not returning the values. If they did, then what you were trying would work. Try it like this:
function getExamGrades()
{
var exam1 = document.getElementById("Exam1").value;
var exam2 = document.getElementById("Exam2").value;
var exam3 = document.getElementById("Exam3").value;
var Exams = Number(exam1) + Number(exam2) + Number(exam3);
document.getElementById("examGrade").innerHTML = Exams;
return Exams;
}
function getLabGrades()
{
var lab1 = document.getElementById("Lab1").value;
var lab2 = document.getElementById("Lab2").value;
var lab3 = document.getElementById("Lab3").value;
var Labs = Number(lab1) + Number(lab2) + Number(lab3);
document.getElementById("labGrade").innerHTML = Labs;
return Labs;
}
function getTotalGrades()
{
var Total = Number(getExamGrades()) + Number(getLabGrades());
document.getElementById("totalGrade").innerHTML = Total;
}
There were a couple of other minor issues that I fixed for you too.
You can see a working example here: http://jsfiddle.net/8js5uewc/2/
I'm trying to have three textareas. The first two are addends and the last is the sum. What's supposed to happen is if your math equation is correct, a paragraph will say true.
Else, it'll say false. However, the paragraph doesn't say anything when I try.
Here's my code:
<textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>
<script>
var x = document.getElementById('x').innerHTML;
var y = document.getElementById('y').innerHTML;
var z = x + y;
var p = document.getElementById('p');
</script>
<button oclick="if (z = document.getElementById('z').innerHTML) {p.innerHTML = true} else {p.innerHTML = false}">Calculate</button>
<br>
<p id="p"></p>
First attaching the click event to your button from the JS code using addEventListener will be better (avoid the inline-events), then put your code inside, you have to use .value insted of innerHTML to get the value of a textarea.
Note also that you should use double equals == when you want to compare two elements, and because we need to perform a math operations we should cast our values to numbers using Number() method.
Should be something like :
document.getElementById("calculate").addEventListener("click", function() {
var x = Number( document.getElementById('x').value );
var y = Number( document.getElementById('y').value );
var z = x + y;
var p = document.getElementById('p');
if (z == document.getElementById('z').value) {
p.innerText = "true";
} else {
p.innerText = "false";
}
});
<textarea id="x"></textarea>
<textarea id="y"></textarea>
<textarea id="z"></textarea>
<button id="calculate">Calculate</button>
<br>
<p id="p"></p>
first of all, I suggest you to use input here instead of
Second thing is, I would suggest you to use function when you use 'onclick'
Here's the result:
<html>
<body>
<input type='number' placeholder='x: (input number please)' id="x" />
<input type='number' placeholder='y: (input number please)' id="y" />
<input type='number' placeholder='z: (input number please)' id="z" />
<br />
<button onclick="CheckByFormula()">Calculate</button>
<br />
<p>Check result: z=x+y ?</p>
<p id="p"></p>
<script type='text/javascript'>
function CheckByFormula(){
var x = parseInt(document.getElementById('x').value);
var y = parseInt(document.getElementById('y').value);
var z = x + y;
//alert('having these params:\n x='+x+' y='+y+' z='+z);
var p = document.getElementById('p');
z1 = parseInt(document.getElementById('z').value);
alert('z1='+z1+' z='+z);
if(z1 == z){
document.getElementById('p').innerHTML = 'true'
}
else {
document.getElementById('p').innerHTML = 'false';
}
}
</script>
</body>
</html>
https://jsfiddle.net/14pm7ypz/2/
I am adding two numbers, but I don't get a correct value.
For example, doing 1 + 2 returns 12 and not 3
What am I doing wrong in this code?
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = y + z;
document.getElementById("demo").innerHTML = x;
}
<p>
Click the button to calculate x.
<button onclick="myFunction()">Try it</button>
</p>
<p>
Enter first number:
<input type="text" id="txt1" name="text1" value="1">
Enter second number:
<input type="text" id="txt2" name="text2" value="2">
</p>
<p id="demo"></p>
They are actually strings, not numbers. The easiest way to produce a number from a string is to prepend it with +:
var x = +y + +z;
I just use Number():
var i=2;
var j=3;
var k = Number(i) + Number(j); // 5
You need to use javaScript's parseInt() method to turn the strings back into numbers. Right now they are strings so adding two strings concatenates them, which is why you're getting "12".
Use parseInt(...) but make sure you specify a radix value; otherwise you will run into several bugs (if the string begins with "0", the radix is octal/8 etc.).
var x = parseInt(stringValueX, 10);
var y = parseInt(stringValueY, 10);
alert(x + y);
Hope this helps!
The following may be useful in general terms.
First, HTML form fields are limited to text. That applies especially to text boxes, even if you have taken pains to ensure that the value looks like a number.
Second, JavaScript, for better or worse, has overloaded the + operator with two meanings: it adds numbers, and it concatenates strings. It has a preference for concatenation, so even an expression like 3+'4' will be treated as concatenation.
Third, JavaScript will attempt to change types dynamically if it can, and if it needs to. For example '2'*'3' will change both types to numbers, since you can’t multiply strings. If one of them is incompatible, you will get NaN, Not a Number.
Your problem occurs because the data coming from the form is regarded as a string, and the + will therefore concatenate rather than add.
When reading supposedly numeric data from a form, you should always push it through parseInt() or parseFloat(), depending on whether you want an integer or a decimal.
Note that neither function truly converts a string to a number. Instead, it will parse the string from left to right until it gets to an invalid numeric character or to the end and convert what has been accepted. In the case of parseFloat, that includes one decimal point, but not two.
Anything after the valid number is simply ignored. They both fail if the string doesn’t even start off as a number. Then you will get NaN.
A good general purpose technique for numbers from forms is something like this:
var data=parseInt(form.elements['data'].value); // or parseFloat
If you’re prepared to coalesce an invalid string to 0, you can use:
var data=parseInt(form.elements['data'].value) || 0;
Just add a simple type casting method as the input is taken in text. Use the following:
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
This won't sum up the number; instead it will concatenate it:
var x = y + z;
You need to do:
var x = (y)+(z);
You must use parseInt in order to specify the operation on numbers. Example:
var x = parseInt(y) + parseInt(z); [final soulution, as everything us]
Simple
var result = parseInt("1") + parseInt("2");
console.log(result ); // Outputs 3
This code sums both the variables! Put it into your function
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = (y +z);
document.getElementById("demo").innerHTML = x;`
<head>
<script type="text/javascript">
function addition()
{
var a = parseInt(form.input1.value);
var b = parseInt(form.input2.value);
var c = a+b
document.write(c);
}
</script>
</head>
<body>
<form name="form" method="GET">
<input type="text" name="input1" value=20><br>
<input type="text" name="input2" value=10><br>
<input type="button" value="ADD" onclick="addition()">
</form>
</body>
</html>
Or you could simply initialize
var x = 0; ( you should use let x = 0;)
This way it will add not concatenate.
If Nothing works then only try this. This maybe isn't Right way of doing it but it worked for me when all the above failed.
var1 - (- var2)
You are missing the type conversion during the addition step...
var x = y + z; should be var x = parseInt(y) + parseInt(z);
<!DOCTYPE html>
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">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 = parseInt(y) + parseInt(z);
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
<input type="text" name="num1" id="num1" onkeyup="sum()">
<input type="text" name="num2" id="num2" onkeyup="sum()">
<input type="text" name="num2" id="result">
<script>
function sum()
{
var number1 = document.getElementById('num1').value;
var number2 = document.getElementById('num2').value;
if (number1 == '') {
number1 = 0
var num3 = parseInt(number1) + parseInt(number2);
document.getElementById('result').value = num3;
}
else if(number2 == '')
{
number2 = 0;
var num3 = parseInt(number1) + parseInt(number2);
document.getElementById('result').value = num3;
}
else
{
var num3 = parseInt(number1) + parseInt(number2);
document.getElementById('result').value = num3;
}
}
</script>
It's very simple:
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">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>
Try this:
<!DOCTYPE html>
<html>
<body>
<p>Add Section</p>
<label>First Number:</label>
<input id="txt1" type="text"/><br />
<label>Second Number:</label>
<input id="txt2" type="text"/><br />
<input type="button" name="Add" value="Add" onclick="addTwoNumber()"/>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
}
function addTwoNumber(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
var x = Number(a) + Number(b);
document.getElementById("demo").innerHTML = "Add Value: " + x;
}
</script>
</body>
</html>
If we have two input fields then get the values from input fields, and then add them using JavaScript.
$('input[name="yourname"]').keyup(function(event) {
/* Act on the event */
var value1 = $(this).val();
var value2 = $('input[name="secondName"]').val();
var roundofa = +value2+ +value1;
$('input[name="total"]').val(addition);
});
This can also be achieved with a more native HTML solution by using the output element.
<form oninput="result.value=parseInt(a.valueAsNumber)+parseInt(b.valueAsNumber)">
<input type="number" id="a" name="a" value="10" /> +
<input type="number" id="b" name="b" value="50" /> =
<output name="result" for="a b">60</output>
</form>
https://jsfiddle.net/gxu1rtqL/
The output element can serve as a container element for a calculation or output of a user's action. You can also change the HTML type from number to range and keep the same code and functionality with a different UI element, as shown below.
<form oninput="result.value=parseInt(a.valueAsNumber)+parseInt(b.valueAsNumber)">
<input type="range" id="a" name="a" value="10" /> +
<input type="number" id="b" name="b" value="50" /> =
<output name="result" for="a b">60</output>
</form>
https://jsfiddle.net/gxu1rtqL/2/
You can do a precheck with regular expression wheather they are numbers as like
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
if((x.search(/[^0-9]/g) != -1)&&(y.search(/[^0-9]/g) != -1))
var x = Number(y)+ Number(z);
else
alert("invalid values....");
document.getElementById("demo").innerHTML = x;
}
Use parseFloat it will convert string to number including decimal values.
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = parseFloat(y) + parseFloat(z);
document.getElementById("demo").innerHTML = x;
}
<p>
Click the button to calculate x.
<button onclick="myFunction()">Try it</button>
</p>
<p>
Enter first number:
<input type="text" id="txt1" name="text1" value="1">
Enter second number:
<input type="text" id="txt2" name="text2" value="2">
</p>
<p id="demo"></p>
You can also write :
var z = x - -y ;
And you get correct answer.
<body>
<input type="text" id="number1" name="">
<input type="text" id="number2" name="">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, y ;
x = document.getElementById('number1').value;
y = document.getElementById('number2').value;
var z = x - -y ;
document.getElementById('demo').innerHTML = z;
}
</script>
</body>
Here goes your code by parsing the variables in the function.
<html>
<body>
<p>Click the button to calculate x.</p>
<button onclick="myFunction()">Try it</button>
<br/>
<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 = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Answer
An alternative solution, just sharing :) :
var result=eval(num1)+eval(num2);
Perhaps you could use this function to add numbers:
function calculate(a, b) {
return a + b
}
console.log(calculate(5, 6))
I want to make a RGB to HEX converter using JS. to do this i did the below code:
function convertToHex(){
var r=document.getElementById("R").value;
var g=document.getElementById("G").value;
var b=document.getElementById("B").value;
if(r>255 || g>255 || b>255){
document.getElementById("error").innerHTML='R ,G, B value can not be greater than 255';
}
else{
var rHex=r.toString(16);
var gHex=g.toString(16);
var bHex=b.toString(16);
var toHex=rHex+gHex+bHex;
document.getElementById("hexContainer").innerHTML=toHex;
}
}
but it is not working. Could you please help me. it is showing the numbers only not converted values.
When you grab the value from HTML, you need to convert the string to number,
you can do
var r = Number(document.getElementById("R").value);
I tested the rest of the code, and they work fine.
You can try out this way. It works perfect.
<body>
<input id="R" type="number">
<br>
<input id="G" type="number">
<br>
<input id="B" type="number">
<br>
<input id="btn" type="button" onclick="rgb2hex()" value="calculate">
<div id= "hexContainer"></div>
<div id="error"></div>
<script>
function rgb2hex() {
var r = document.getElementById("R").value
var g = document.getElementById("G").value
var b =document.getElementById("B").value
if (r> 255 || g> 255 || b> 255){
document.getElementById( "error" ).innerHTML= 'R ,G, B value can not be greater than 255' ;
document.getElementById( "hexContainer").innerHTML=""
}
else {
document.getElementById( "hexContainer").innerHTML= ("#"+dec2Hex(Math.round(r)) +""+ dec2Hex(Math.round(g)) +""+dec2Hex(Math.round(b)));
document.getElementById( "error").innerHTML=""
}
}
function dec2Hex(decimal) {
return ("0"+(Number(decimal).toString(16))).slice(-2).toUpperCase()
}
</script>
</body>
function convertToHex(){
var r=document.getElementById("R").value;
var g=document.getElementById("G").value;
var b=document.getElementById("B").value;
if(+r>255 || +g>255 || +b>255){
document.getElementById("error").innerHTML='R ,G, B value can not be greater than 255';
}
else{
var rHex=(+r).toString(16);
var gHex=(+g).toString(16);
var bHex=(+b).toString(16);
var toHex=rHex+gHex+bHex;
document.getElementById("hexContainer").innerHTML=toHex;
}
}
I previously posted a code with the similar way and I am still having problems with it. this time I get 100.0712.5 when I put 10 as the bill, 7 for the sales tax and 25 for the tip. I am really new to Javascript coding and I have literally been spending hours trying to figure this out I need help.
<html>
<head>
<script type="text/javascript">
function applyTax(){
var inputAmount = document.getElementById( 'dollars' ).value;
var salesTax = document.getElementById( 'tax' ).value;
var tip = document.getElementById( 'tip' ).value;
var totalAmount = (salesTax/100) + (inputAmount);
var tipprcnt = (tip/100) * (inputAmount);
var Grandtotal = (inputAmount + (totalAmount*1) + (tipprcnt*1));
//document.getElementById( 'requestedAmount' ).innerHTML = tipprcnt;
//document.getElementById( 'requestedTax' ).innerHTML = totalAmount;
document.getElementById( 'requestedGrand' ).innerHTML = Grandtotal;
}
</script>
</head>
<body>
<h1>Sales Tax + Tip Calculator</h1>
<p>Type in your price (dollar amount). Click the "Calculate" button to receive your total.
</p>
<p>
What is the bill amount?: $<input type="text" id="dollars" /> <br>
What is the sales tax?:<input type="text" id="tax" />%<br>
how much do you want to tip?:<input type="text" id="tip" />%
<input type="button" onclick="applyTax();" value="Calculate" />
</p>
</h2>The Grand Total is:</h2>
<div id="requestedAmount"> </div>
<div id="requestedTax"> </div>
<div id="requestedGrand"> </div>
<p>Home
</body>
</html>
You were adding them as string, use parseFloat instead
http://plnkr.co/edit/6pN2Ug5qxcOSUjE5AnhJ?p=preview
function applyTax(){
var inputAmount = parseFloat(document.getElementById( 'dollars' ).value);
var salesTax = parseFloat(document.getElementById( 'tax' ).value);
var tip = parseFloat(document.getElementById( 'tip' ).value);
var taxprcnt = (salesTax/100) * (inputAmount);
var tipprcnt = (tip/100) * (inputAmount);
var Grandtotal = inputAmount + taxprcnt + tipprcnt;
document.getElementById( 'requestedGrand' ).innerHTML = Grandtotal.toFixed(2); // Round to 2 decimals
}
You should use parseFloat() to convert the inputs to numbers.
You need to multiply the input amount by the tax percentage, not add them.
You should round off the final result, because people don't want to see fractional pennies.
DEMO
When I enter $10 amount, 7% tax, 25% tip, the total is $13.20.
Use Number(input.value) by every input to convert the string values into numbers. You can use parseInt() or parseFloat instead of Number() if you want. The first converts to integer, the second converts to numbers with decimal points.
Btw forget the overusage of () and *1, it is just noise for others...
Your variable names are confusing, but I guess you wanted something like this:
var amountInput = document.getElementById("dollars");
var taxInput = document.getElementById("tax");
var tipInput = document.getElementById("tip");
var amount = Number(amountInput.value);
var taxPercent = Number(taxInput.value);
var tipPercent = Number(tipInput.value);
var grandTotal = Math.round(amount * (100 + taxPercent + tipPercent)) / 100;
var grandTotalOutput = document.getElementById("requestedGrand");
grandTotalOutput.innerHTML = grandTotal;