Javascript flashing for a second but not printing in textbox - javascript

Amount
<script type="text/javascript">
<!--
function interestVal()
{
var x = document.Amounts.valOfCar.value;
var y = document.Amounts.interestofCar.value;
var z = x+y;
document.Amounts.carInterest.value=z;
}
-->
</script>
</head>
<body background="bg.jpg">
<p>Calculate the cost of your car</p>
<form name = Amounts>
<p>Value of a car <input type="text" value="" name=valOfCar></p>
<p>Interest #15% <input type="text" value="" name=interestofCar></p>
<p>Value + Interest<input type="text" name=carInterest></p>
<p><input type=submit value=Calculate onClick=interestVal()></p>
</form>
</body>

Here you go. I was able to reproduce your problem by just copying your code and running it. This code will run. The principal change I made, which I believe was the source of the problem, was altering from an input of type submit to a button. As a submit, it was doing a postback, which caused the contents of the controls to disappear. Using a button avoids the postback.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
<!--
function interestVal() {
var x = document.Amounts.valOfCar.value;
var y = document.Amounts.interestofCar.value;
var z = x * y;
document.Amounts.carInterest.value = z;
}
-->
</script>
</head>
<body background="bg.jpg">
<p>Calculate the cost of your car</p>
<form name = "Amounts">
<p>Value of a car <input type="text" name="valOfCar" /></p>
<p>Interest #15% <input type="text" name="interestofCar" /></p>
<p>Value + Interest<input type="text" name="carInterest" /></p>
<p><button type="button" onclick="interestVal();" >Calculate</button></p>
</form>
</body>
</html>
Another potential problem is that by summing x and y, you get their concatenated result, which is probably not what you want. I have changed that to multiplying x times y.
Finally, I have enclosed many of the attribute values in quotes and made the inputs self-closing by ending the with /> instead of >.

Related

My results of calculation appear on a different page

I need to create code which automatticaly calculates the circumference when the length and width are entered in two different boxes.
I managed to do so, but I want the answer to appear underneath the "calculate" button, but the answer will make the button and boxes disappear. Could someone tell me what I need to change?
Here is my code:
<!DOCTYPE html>
<html>
<body>
<form>
Width:<br>
<input id="Width" type="text" name="Width">
<br>Length<br>
<input id="Length" type="text" name="Length">
<br><br>
<input type="button" value="Calculate circumference" onclick="doMath()">
</form>
<script>
function doMath() {
var Width1 = document.getElementById('Width').value;
var Length1 = document.getElementById('Length').value;
var Circ = parseInt(Width1) + parseInt(Width1) + parseInt(Length1) + parseInt(Length1);
document.write(Circ);
}
</script>
</body>
</html>
Do not use document.write function. The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML. Create a paragraph tag and give an id and place your result in that paragraph.
<!DOCTYPE html>
<html>
<body>
<form>
Width:<br>
<input id="Width" type="text" name="Width">
<br>Length<br>
<input id="Length" type="text" name="Length">
<br><br>
<input type="button" value="Calculate circumference" onclick="doMath()">
<p id="result">
</p>
</form>
<script>
function doMath() {
var Width1 = document.getElementById('Width').value;
var Length1 = document.getElementById('Length').value;
var Circ = parseInt(Width1) + parseInt(Width1) + parseInt(Length1) + parseInt(Length1);
//document.write(Circ);
document.getElementById("result").textContent = Circ;
}
</script>
</body>
</html>
Try adding a black paragraph to the html and then use document.getElementById("").innerHTML to change the text inside of it.

Form with input and output immediately reload the page after printing the output

I need to do a simple homework where you enter two integers in two text fields of a form and then you compute the sum and you print it in a "text field (not editable)". My program seems to work but it prints the right output and immediately reload the page. I want the page to remain with the printed output if the user does not click again on "submit" button
Here is my code HTML & JS :
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form>
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
</html>
When form is submited, the page will be reloaded. To prevent this you should change input type attribute from submit to button.
<input type="submit" value="Submit" onClick="updateExpr()"/>
to
<input type="button" value="Submit" onClick="updateExpr()"/>
You can simply avoid server call by changing your form tag
<form onSubmit="return false">
You dont really need a form to do something like this.
Forms send values to the backend, e.g. a server.
You only want to manipulate some front-end elements like a container to have some new text inside it.
a <form> tag typically sends you to some URI with some aprameters,
this is done by the actions attribute.
<form action="addnames.php">
for example would call the addnames.php script on your server...
You dont need a server tho..look below:
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum =x1 +x2;
document.getElementById("sum").innerHTML = sum;
}
<h2>HTML Forms</h2>
First name:<br>
<input id="n1" type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input id="n2" type="text" name="lastname" value="Mouse">
<br><br>
<button type="submit" onclick="updateExpr()">Submit</button>
<div id="sum">
</div>
<script>
</script>
I would recommand you to add onSubmit method to the form instead of onclick to the input.
Also you better add a return : false to your function and add onsubmit="return updateExpr()".
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
return false;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form onsubmit="return updateExpr()">
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
Another way of doing this would have been to add a button outside of the form linked to the function by onclick event
juste add preventDefault(), like this
function updateExpr(e) {
e.preventDefault();
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}

Answer does not get shown in a message box

I have 2 random numbers being generated determined by the user input. I then have a box where you enter your answer to the addition problem, but it does not show whether you are right or not.
I've tried changing the buttons and what kind of message they output.
<html>
<head>
<title>Math</title>
<h1>Math Questions<h1/>
<link href="Style.css" rel="stylesheet">
<script type="text/javascript">
function RandomNum1() {
var low = parseFloat(document.getElementById("Low").value);
var high = parseFloat(document.getElementById("High").value);
var Random;
Random = Math.floor((Math.random()*high )+ low);
document.getElementById("output").innerHTML = Random;
}
function RandomNum2() {
var low2 = parseFloat(document.getElementById("Low").value);
var high2 = parseFloat(document.getElementById("High").value);
var Random2;
Random2 = Math.floor((Math.random()*high2 )+ low2);
document.getElementById("output2").innerHTML = Random2;
}
function Answer(userGuess) {
var answer = Random+Random2;
if (userGuess==answer) {
document.getElementById("outMsgBox").innerHTML="You are correct!!!";
} else {
document.getElementById("outMsgBox").innerHTML="Sorry, try again. :(";
}
}
</script>
</head>
<body>
<p>Enter the range of numbers you would like. <br />
Minimum <input type="numeric" id="Low" size="10" value="" /> <br />
Maximum <input type="numeric" id="High" size="10" value="" />
</p>
<input type="button" value="Generate First " onclick="RandomNum1();" hr="" /> <input type="button" value="Generate Second" onclick="RandomNum2();" hr="" />
<p><div id="output" type="numeric"></div>+<div class="OutputBox" id="output2" type="numeric"></div></p>
<p>Enter your answer here. <input type=numeric id="userGuess" min="1" max="1000"/> </p>
<input type="button" style="background-color:lightgreen" value="Check Answer" onclick="Answer(document.getElementById('userGuess').value);"/>
<div id="outMsgBox" style="border-style:groove; border-color:green"></div>
</body>
</html>
It's supposed to show if you answered right or not but it does not show anything when you click "check answer".
The problem is that you are declaring the variables Random, Random2 as a local variable.
Try placing this line at the start of the script
var Random, Random2;
This will define them as global variables, which means any part of your script can acces the variables. You then need to remove the definitions for the variables var Random and var Random2from the functions so you don't override the global variables.

Adding Number by javascript

<html>
<head>
<title>JavaScript - using function</title>
<script>
function add(){
var value1=document.getElementById("n1").value;
var value2=document.getElementById("n2").value;
document.getElementById("result").value=parseFloat(value1)+parseFloat(value2);
}
</script>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onClick="add()" />
<p>
Result = <span id="result" ></span>
</p>
</body>
</html>
I am new to JavaScript and wanted to create a script that add numbers up. After pressing "Add" button, I cannot get the result to be displayed. How to get the result displayed?
Two things wrong here...
1)
<input type="button" value="Add" /> change it to
<input type="button" value="Add" onclick="add()" />
Also,
2)
document.getElementById("result").value=parseFloat(value1)+parseFloat(value2);
to
document.getElementById("result").innerHTML=parseFloat(value1)+parseFloat(value2);
PS : This is not a assignment solving website :P
First, You Should Change
document.getElementById("result").value = value1 + value2
To This:
document.getElementById("result").innerHTML = n1 + n2
Because value stands for the attribute value for < input >, not the text written
in the tag.
Second, Change The Button Code To:
<input type="button"value="Add"onclick="add()">
This "onclick" is something called event in javascript,
It means at clicking on the button "Add" it performs the funtion called "add()".
If You Are New To Javascript You Will Know Everything.
Just Be Patient.
It worked with the following changes
-> calling add function with onclick event
-> using innerhtml in place of value
<html>
<head>
<title>JavaScript - using function</title>
<script>
function add(){
var value1=document.getElementById("n1").value;
var value2=document.getElementById("n2").value;
console.log(value1,value2)
document.getElementById("result").innerHTML=parseFloat(value1)+parseFloat(value2);
}
</script>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onclick="add()"/>
<p>
Result = <span id="result" ></span>
</p>
</body>
</html>
Hope this helps
Its better to put the js at the end of the document - also as noted the onclick handler needs to call the function. I also tidied up the code a little.
<html>
<head>
<title>JavaScript - using function</title>
<style>label{display:block}</style>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onclick="add()">
<p>Result = <span id="result" ></span></p>
<script>
function add(){
var value1=parseFloat(document.getElementById("n1").value);
var value2=parseFloat(document.getElementById("n2").value);
var total= value1 + value2;
document.getElementById("result").innerText=total;
}
</script>
</body>
</html>

Why javascript is returning NaN when I place variables outside the function?

Do you guys know whyn when I place this varables outside the functions, the result is "Not a Number"?.
Dont variables should become "Global" when placed ouside a function?
<html>
<head>
<script type="text/javascript">
// V-LOXY > Variaveis Calculo de Frete
var Comp = document.getElementById('ComprimenTo').value;
var Larg = document.getElementById('Largura').value;
var Alt = document.getElementById('Altura').value;
var TxCubagem = 300
function PesoCubado(){
document.getElementById('PesoCub').innerHTML = ((Comp/100)*(Larg/100)*(Alt/100)*TxCubagem).toFixed(1)+' kg';
}
</script>
</head>
<body>
<label>Comprimento [cm]:
<input id='ComprimenTo' type="number" width="15"/></label><br />
<p></p>
<label>Largura [cm]:
<input id='Largura' type="number" width="15"/></label><br />
<p></p>
<label>Altura [cm]:
<input id='Altura' type="number" width="15"/></label><br />
<p></p>
<input type='button' onclick='PesoCubado()' value="Calcular" >
<p></p>
<p>Peso Cubado: <b id='PesoCub'></b> </p>
</body>
</html>
You need to do 2 things: move your script to below your elements that you are trying to do work on (right before end of body closing), and grab the value of the inputs during the PesoCubado() function invocation:
<html>
<head></head>
<body>
<label>Comprimento [cm]:
<input id='ComprimenTo' type="number" width="15"/></label><br />
<p></p>
<label>Largura [cm]:
<input id='Largura' type="number" width="15"/></label><br />
<p></p>
<label>Altura [cm]:
<input id='Altura' type="number" width="15"/></label><br />
<p></p>
<input type='button' onclick='PesoCubado()' value="Calcular" >
<p></p>
<p>Peso Cubado: <b id='PesoCub'></b> </p>
<script type="text/javascript">
var CompElem = document.getElementById('ComprimenTo');
var LargElem = document.getElementById('Largura');
var AltElem = document.getElementById('Altura');
var PesoCubElem = document.getElementById('PesoCub');
var TxCubagem = 300
function PesoCubado(){
PesoCubElem.innerHTML = ((CompElem.value/100)*(LargElem.value/100)*(AltElem.value/100)*TxCubagem).toFixed(1)+' kg';
}
</script>
</body>
</html>
You've got several problems with your script, which are:
your variables point to the initial value of the text fields, and as such, won't be using the latest value. You should get the values of each field within your PesoCubado function.
Values returned from inputs are always strings and as such, you'll have to convert them to a number using the Number function.
You'd be best wrapping your code in a load event listener on the window to ensure your page is loaded fully.
Hopefully this helps.
Tom

Categories