Ive stared to learn Javascript, im trying to create a calculator, which just multiplies 2 numbers, i get this error in my browser console.
Can anybody help?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calc</title>
<style>#result{position: relative; top: 5px;}</style>
</head>
<body>
<input type="number" id="first"> *
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
<script>
function res() {
var a = document.getElementById("first").value;
var b = document.getElementById("second").value;
var span = document.getElementById("span");
if(a != 0 && b !=0) {
span.innerHTML = a * b;
}
if(a = 0 || b = 0) {
span.innerHTML = "0"; // I know browser can do it automatically without 21 and 22 strings but i need that it works this way.
}
}
</script>
</body>
</html>
Firstly, if you are going to do any math with text input, you have to convert them to a number. You can use parseInt(num, 10) or parseFloat(num).
Secondly, in one of your if-statements, you are not actually comparing the variables a and b, but assigning 0 to them. Use two equal signs == to compare variables.
Thirdly, you could just check for whether they are numbers instead using isNaN(num). Doing so would eliminate the first if-statement.
function res() {
var a = parseFloat(document.getElementById("first").value);
var b = parseFloat(document.getElementById("second").value);
var span = document.getElementById("span");
if (isNaN(a) || isNaN(b)) {
span.innerHTML = "0";
}
else {
span.innerHTML = a * b;
}
}
<input type="number" id="first">*
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
check here your corrected code
<html>
<head>
<title>Calc</title>
<style>#result{position: relative; top: 5px;}</style>
</head>
<body>
<input type="number" id="first"> *
<input type="number" id="second">
<br>
<input type="submit" id="result" value="Check out" onclick="res()"></input> <span id="span"></span>
<script>
function res() {
var a = document.getElementById("first").value;
var b = document.getElementById("second").value;
var span = document.getElementById("span");
if(a != 0 && b !=0) {
span.innerHTML = a * b;
}
if(a == 0 || b == 0) {
span.innerHTML = "0"; // I know browser can do it automatically without 21 and 22 strings but i need that it works this way.
}
}
</script>
</body>
</html>
Related
The problem is solved no need to go thorough the post thanks for the help the useful time is appreciated.
you are referencing this DOM object (<span id = "res"></span>) itself but you don't want this object but the text which is stored inside.
You would get this value with a simple
document.getElementById("res").innerText
That's more or less the same call you are using to set the text of this res object.
So a working example could look like this
<!DOCTYPE html>
<html>
<head>
<title> Exercise 2 </title>
</head>
<body>
<form>
Enter the value to be converted <br><br> <input type="numbers" id="val" /> <br><br>
<input type="button" onClick="celtofar()" Value="Celcius to Fahrenhet" id="b1" /><br><br>
<input type="button" onClick="fartocel()" Value="Fahrenhet to Celcius" id="b2"/><br><br>
Output : <br>
<span id = "res"></span>
<p id= "op"></p>
</form>
<style type="text/css">
body { margin-left: 450px; margin-top: 100px}
</style>
<script type="text/javascript">
function celtofar()
{
v = document.getElementById("val").value;
document.getElementById("res").innerHTML = (v * 1.8) + 32;
var message = v +'\xB0C is ' + document.getElementById("res").innerText + '\xB0F.';
document.getElementById("op").innerHTML = message;
}
function fartocel()
{
v = document.getElementById("val").value;
document.getElementById("res").innerHTML = (v - 32) / 1.8;
var message = v +'\xB0F is ' + document.getElementById("res").innerText + '\xB0C.';
document.getElementById("op").innerHTML = message;
}
</script>
</body>
</html>
Read more about this here:
https://www.w3schools.com/js/js_htmldom.asp
you just need to close the span after the <p></p> tag. Just put the closing </span> after the </p>
<span id = "res">
<p id= "op"></p></span>
I am attempting to make a calculator in order to... well, calculate something. Anyway, I am trying to make 4 variables be set too 4 user inputs by using form submission. However, no matter what I do, I can't get the variables to get set. Help would be appreciated!
<!DOCTYPEhtml>
<html>
<head>
<title>NatHisCalc</title>
</head>
<body>
<h1><center><b><p>Test</p></b></center></h1>
<center><b><p id='output'>loading...</p></b></center>
<center><b><p id='output2'>loading...</p></b></center>
<center><b><p id='output3'>loading...</p></b></center>
<center><b><p id='output4'>loading...</p></b></center>
<form id="a" action="/action_page.php">
Input X <input type="number" name="x"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<form id="a" action="/action_page.php">
Input X <input type="number" name="y"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<form id="a" action="/action_page.php">
Input X <input type="number" name="a"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<form id="a" action="/action_page.php">
Input X <input type="number" name="b"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<script>
function calc() {
var x = document.getElementById("x").submit();
var y = document.getElementById("y").submit();
var a = document.getElementById("a").submit();
var b = document.getElementById("b").submit();
var u = (0.101*(y/100))*(480000*(a/100))
var j = (0.581*(x/100))*(120000*(b/100))
if (x > 150 || x < 50) {
window.alert('Hold on... Those inputs will result in an unreasonable output. You can click ');
}
var preresult = j + u;
if (preresult < 177000) {
document.getElementById('output').innerHTML = 'Test';
} else {
document.getElementById('output').innerHTML = 'Test1';
}
if (u > 179999) {
document.getElementById('output').innerHTML = 'Test2';
}
document.getElementById('output2').innerHTML = 'Test3' + j;
document.getElementById('output3').innerHTML = 'Test4 ' + u;
document.getElementById('output4').innerHTML = 'Test5 ' + preresult;
}
</script>
</body>
</html>
Looked into your code, it seems that you have made things way too much complicated that it should be. First of all, you don't call submit function on the input to get the value of it. If you want to get the value of x then you just access the value property like this document.getElementById("x").value. Secondly, you really don't need four buttons, all you need to do is ONE button that submits the form and adding required on input fields makes the browser not submit the form until all forms are filled. Last of all, id attribute needs to be unique across your page. You have both form and input field as id a which is unacceptable. It will show no error but get you in sorts of trouble. You can see what I did here, where I prevented the form from being submitted upon the button click and simply called the calc function to perform the calculation.
<!DOCTYPEhtml>
<html>
<head>
<title>NatHisCalc</title>
</head>
<body>
<h1><center><b><p>Test</p></b></center></h1>
<center><b><p id='output'>loading...</p></b></center>
<center><b><p id='output2'>loading...</p></b></center>
<center><b><p id='output3'>loading...</p></b></center>
<center><b><p id='output4'>loading...</p></b></center>
<form onsubmit="event.preventDefault(); calc();" action="/action_page.php">
Input X <input type="number" id="x" required><br><br>
Input Y <input type="number" id="y" required><br><br>
Input A <input type="number" id="a" required><br><br>
Input B <input type="number" id="b" required><br><br>
<input type="submit" value="Submit">
</form>
<script>
function calc() {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var u = (0.101*(y/100))*(480000*(a/100))
var j = (0.581*(x/100))*(120000*(b/100))
if (x > 150 || x < 50) {
window.alert('Hold on... Those inputs will result in an unreasonable output. You can click ');
}
var preresult = j + u;
if (preresult < 177000) {
document.getElementById('output').innerHTML = 'Test';
} else {
document.getElementById('output').innerHTML = 'Test1';
}
if (u > 179999) {
document.getElementById('output').innerHTML = 'Test2';
}
document.getElementById('output2').innerHTML = 'Test3' + j;
document.getElementById('output3').innerHTML = 'Test4 ' + u;
document.getElementById('output4').innerHTML = 'Test5 ' + preresult;
}
</script>
</body>
</html>
I am new to Javascript and just getting into it for my web design class. I am working on a project with Javascript inside HTML. I have it all written, but the HTML doesn't seem to call the Javascript function. I've been searching for a solution but can't seem to get anything to work. The code is:
<html>
<head>
<script>
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
if ((interestRate >= 0) && (interestRate <= 15)) {
rate = interestRate / 100;
if ((principleAmount >= 0) && (principleAmount <= 10000)) {
total = principleAmount * (1 + rate * years);
document.getElementById("total_with_intrest").value = total;
}
else {
message-box ("Invalid data for principle amount.");
}
}
else {
message-box ("Invalid data for interest rate.");
}
}
</script>
<style>
form{ border: solid blue;
width:40em;
padding:0.5em;}
input{padding: 0.5em;}
</style>
</head>
<body>
<form>
Enter Principal Ammount : <input type="text" id ="principal" />
</br>
Enter Intrest Rate : <input type="text" id ="intrest" />
</br>
Enter Number of Years : <input type="text" id ="years" />
</br>
Grand Ammount : <input type="text" id ="total_with_intrest" disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick=calculateInterest()/> </br>
</form>
</body>
</html>
The browser error is "SyntaxError: expected expression, got '}' " on line 2 but I just can't see what the issue is. Any help is greatly appreciated!
Side note, I am aware there are some weird spelling mistakes. My instructor is from India and not totally fluent in English. She made the HTML file for us to use and we just have to put in the Javascript.
There is no message-box function. Did you mean alert()? Your code currently works, with those changes:
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
if ((interestRate >= 0) && (interestRate <= 15)) {
rate = interestRate / 100;
if ((principleAmount >= 0) && (principleAmount <= 10000)) {
total = principleAmount * (1 + rate * years);
document.getElementById("total_with_intrest").value = total;
}
else {
alert("Invalid data for principle amount.");
}
}
else {
alert("Invalid data for interest rate.");
}
}
form{ border: solid blue;
width:40em;
padding:0.5em;}
input{padding: 0.5em;}
<form>
Enter Principal Amount : <input type="text" id ="principal" />
</br>
Enter Interest Rate : <input type="text" id ="intrest" />
</br>
Enter Number of Years : <input type="text" id ="years" />
</br>
Grand Amount : <input type="text" id ="total_with_intrest" disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick="calculateInterest()" /> </br>
</form>
Small Nitpick: Fixed some small typos not related to code. Ammount => Amount. Intrest => Interest.
I am trying to make an simple math test that has 10 problems. They have to display one at a time. I have hit a roadblock and I'm not sure how to move forward from here. I made a submit button and I figured I could just load the next question onClick load but it's a little more complicated than I thought.Any advice would be greatly appreciated.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Interactive Math Worksheet</title>
<script type="text/javascript">
var mathProblem = new Array();
var carryOver = document.getElementById("carry");
var correct = 0;
var wrong = 2;
// writing the problem 10 times
function writeProblem(){
for (var i=1; i<11; i++){
num1 = (Math.floor(Math.random()*50)+1);
num2 = (Math.floor(Math.random()*50)+1);
document.getElementById("top"+i).innerHTML = num1;
document.getElementById("bottom"+i).innerHTML = "+" + num2;
mathProblem[i] = num1 + num2;
document.forms["problem"+i]["answer"+i].value = "";
}
}
function submitAnswer(){
var i=0;
for (i=1;i<11;x++) {
if (document.forms["problem"+i]["answer"+i].value == mathProblem[i]) {
return true;
}
else if(isNaN (document.forms["problem"+i]["answer"+i].value)){
alert("This is not a spelling test please use numbers");
return false;
}
}
}
</script>
</head>
<body onload="writeProblem()">
<h2>Practicing Your Pluses!</h2>
<form name="problem1">
<input type="text" size="1" name="carry1"><br/>
<label id="top1"></label><br />
<label id="bottom1"></label><br /><hr width="60px" align="left"/>
<input type="text" size="3" name="answer1">
</form><br/>
<input type="button" onClick="submitAnswer()" value="Submit Answers"/>
</body>
</html>
I think This above code gives this Error
Uncaught TypeError: Cannot set property 'innerHTML' of null
Because in your code writeProblem() function has mistake, by the time the function call document read only the element with id "top1" another ids are not there but you are repeting the loop 11 times, so change the onload function body according to the standards of Javascript
I have updated the code please check once JS Fiddle
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Interactive Math Worksheet</title>
<script type="text/javascript">
var mathProblem = new Array();
var carryOver = document.getElementById("carry");
var correct = 0;
var wrong = 2;
// writing the problem 10 times
function writeProblem(){
for (var i=1; i<11; i++){
num1 = (Math.floor(Math.random()*50)+1);
num2 = (Math.floor(Math.random()*50)+1);
document.getElementById("top").innerHTML = num1;
document.getElementById("bottom").innerHTML = "+" + num2;
mathProblem[i] = num1 + num2;
document.forms["problem"]["answer"].value = "";
}
}
function submitAnswer(){
var i=0;
for (i=1;i<11;i++) {
if (document.forms["problem"]["answer"].value == mathProblem[i]) {
writeProblem();
return true;
}
else if(isNaN (document.forms["problem"]["answer"].value)){
alert("This is not a spelling test please use numbers");
return false;
}
}
}
</script>
</head>
<body onload="writeProblem()">
<h2>Practicing Your Pluses!</h2>
<form name="problem">
<input type="text" size="1" name="carry1"><br/>
<label id="top"></label><br />
<label id="bottom"></label><br /><hr width="60px" align="left"/>
<input type="text" size="3" name="answer">
</form><br/>
<input type="button" onClick="submitAnswer()" value="Submit Answers"/>
</body>
</html>
SOLUTION
Avoid using onload, onclick or any inline event or style (read more)
NOTE: In this solution I'm using classList that aint fully supported.
HTML
<div>
<label class="top"></label><br />
<label class="bottom"></label><br />
<hr />
<input class="answer" type="text">
</div>
<div>
<label class="top"></label><br />
<label class="bottom"></label><br />
<hr />
<input class="answer" type="text">
</div>
<div>
<label class="top"></label><br />
<label class="bottom"></label><br />
<hr />
<input class="answer" type="text">
</div>
<input id="submit" type="button" value="Submit"/>
CSS
div, input {
width: 60px;
}
label {
float: right;
padding-right: 10px;
}
.invalid {
border: 1px solid red;
}
JS
var mathProblem = [];
var tops = document.getElementsByClassName('top');
var bottoms = document.getElementsByClassName('bottom');
var answers = document.getElementsByClassName('answer');
function writeProblem(){
for (var i=0; i<3; i++){
num1 = (Math.floor(Math.random()*50)+1);
num2 = (Math.floor(Math.random()*50)+1);
tops[i].innerHTML = num1;
bottoms[i].innerHTML = '+' + num2;
mathProblem[i] = num1 + num2;
}
}
window.addEventListener('load', writeProblem);
function submitAnswer(){
var invalid = document.getElementsByClassName('invalid');
for(var i=0; i<invalid.length; i++){
invalid[i].classList.remove('invalid');
}
var correct = 0;
var wrong = 0;
for (var a=0; a<3; a++) {
var answer = answers[a];
if(isNaN(Number(answer.value))){
answer.classList.add('invalid');
alert('This is not a spelling test, please use numbers');
return false;
}
if(answer.value === ''){
answer.classList.add('invalid');
alert('Answer all questions please');
return false;
}
if (Number(answer.value) === mathProblem[a]) {
correct++;
}
else {
answer.classList.add('invalid');
wrong++;
}
}
alert('Correct: ' + correct + '\nWrong: ' + wrong);
}
document.getElementById('submit')
.addEventListener('click', submitAnswer);
I'm trying to make a triangle missing leg calculator. First you put one leg, the hypotenuse, then you will get the missing leg. But, if you fill in the second box first, It will say NaN. I know its not that important, but is there a way to get rid of it so it says "0" until both boxes are filled? And here is the code:
<html>
<head>
<script type="text/javascript">
function missingleg(a,c){
return Math.sqrt(c*c - a*a);
}
</script>
</head>
<body>
<input type="button" value="Missing Leg";" />
Leg:<input type="text" id="leg" size="2";" />
Hypotenuse:<input type="text" id="hypo" size="2"onChange="document.getElementById('lostleg').value=missingleg(parseInt(document.getElementById('leg').value),parseInt(document.getElementById('hypo').value)); " />
Missing Leg:<input type="text" placeholder="0" id="lostleg" size="2" />
</body>
</html>
Same thing here...
<html>
<head>
<script type="text/javascript">
function hypotenuse(a,b){
return Math.sqrt(a*a + b*b);
}
</script>
</head>
<body>
<input type="button" value="Hypoteneuse";" />
A:<input type="text" id="leg1" size="2";" />
B:<input type="text" id="leg2" size="2" onChange="document.getElementById('result').value=hypotenuse(parseInt(document.getElementById('leg1').value),parseInt(document.getElementById('leg2').value));" />
Hypotenuse:<input type="text" placeholder="0" id="result" size="2" />
</body>
</html>
Try modifying your missingleg function to this:
function missingleg(a,c) {
if ( isNaN(a) || isNaN(c) ) {
return 0;
}
return Math.sqrt(c*c - a*a);
}
A NOTE ON STYLE ISSUES
For purely stylistic purposes, I'd try to put as little code in the markup as possible. Keeping code out of the markup will make it easier to debug should it become necessary later. Introduce a new function, updateMissingLeg(), and put have your HTML call it like this:
<input type="text" id="hypo" size="2" onChange="updateMissingLeg()" />
As a bonus, you could move your isNaN() checks into that function to keep the missingleg() simpler:
function missingleg(a,c){
return Math.sqrt(c*c - a*a);
}
function updateMissingLeg() {
var a = parseInt(document.getElementById('leg').value);
var c = parseInt(document.getElementById('hypo').value);
if ( isNaN(a) || isNaN(c) ) {
document.getElementById('lostleg').value = '';
return;
}
var lostleg = missingleg(a, c);
document.getElementById('lostleg').value = lostleg;
}
As a further bonus, you can call the same updateMissingLeg() function from both text box controls.
UPDATE 2
As requested, here's the whole thing:
<html>
<head>
<script type="text/javascript">
function missingleg(a,c){
return Math.sqrt(c*c - a*a);
}
function updateMissingLeg() {
var a = parseInt(document.getElementById('leg').value);
var c = parseInt(document.getElementById('hypo').value);
if ( isNaN(a) || isNaN(c) ) {
document.getElementById('lostleg').value = '';
return;
}
var lostleg = missingleg(a, c);
document.getElementById('lostleg').value = lostleg;
}
</script>
</head>
<body>
Leg: <input type="text" id="leg" size="2"
onChange="updateMissingLeg()" />
Hypotenuse: <input type="text" id="hypo" size="2"
onChange="updateMissingLeg()" />
Missing Leg: <input type="text" placeholder="0" id="lostleg" size="2" />
</body>
</html>
And a jsfiddle to play with it can be found here.
For a quick and dirty solution, use the ternary operator:
function missingleg(a,c){
return (isNaN(a) || isNaN(c)) ? 0 : Math.sqrt(c*c - a*a);
}
You could also make it less obtrusive and do the parsing in the function:
function missingleg() {
var a = parseInt(document.getElementById('leg').value, 10),
c = parseInt(document.getElementById('hypo').value, 10);
document.getElementById('lostleg').value = (isNaN(a) || isNaN(c)) ? 0 : Math.sqrt(c*c - a*a);
}