I am learning some more JavaScript and am having trouble getting a temperature conversion exercise to run.
The below is what I've written so far with the code commented out being a formula from an earlier exercise I did from my instruction book.
Here's the code:
<!--
Challenge:
Write a function to take a temperature in Celsius as an argument and return the equivalent temperature in Fahrenheit, basing it on the code from Hour 2.
<!DOCTYPE html>
<html>
<head>
<title>Fahrenheit From Celsius</title>
</head>
<body>
<script>
var cTemp =40; // temperature in Celsius
// Let's be generous with parentheses
var hTemp = ((cTemp * 9))/5 + 32;
document.write ("Temperature in Celsius: " + cTemp + " degrees<br/>");
document.write ("Temperature in Fahrenheit: " + hTemp + " degrees");
</script>
</body>
</html>
-->
<html>
<head>
<script>
var cTemp =40; // temperature in Celsius
// Let's be generous with parentheses
var hTemp = ((cTemp * 9))/5 + 32;
</script>
</head>
<body>
<script>
function conversion(a, b) {
var a = 10;
var b = hTemp;
alert (conversion);
}
</script>
<input type="button" value="Click for Conversion" onclick="conversion() " />
</body>
</html>
Right now when I run the code is displays all the code of the conversion function but doesn't actually convert!
I have been going through this for hours and I feel like the right answer isn't too far away. My question in a nutshell: What do I need to correct to get this to run properly?
Help would be appreciated as I am keen to keep coding but have hit a brick wall here.
You have written alert(conversion), which will basically display the function code, since conversion is a reference to the function.
One other thing, your conversion function takes two variables a and b which is unnecessary as you are not passing any parameters while calling it.
Here is what you can do:
<html>
<head>
<script>
function conversion() {
let cTemp =40; // temperature in Celsius
let hTemp = ((cTemp * 9))/5 + 32;
alert (hTemp);
}
</script>
</head>
<body>
<input type="button" value="Click for Conversion" onclick="conversion() " />
</body>
</html>
Since you are learning, you should start using best practices. Avoid var for variable declaration and use let instead, as it is block scoped. Instead of using alert you can also use console.log to print values in developer console. I would advise you to search for some tutorials on Google Chrome Developer Tools.
There are several problems with your solution:
You are passing a function to the alert and not the result of the function.
In Javascript you can pass around functions as variables. So if you do alert(conversion), you tell the browser to show the actual function code to the user.
To execute the function, you put parantheses after the function name:
alert(conversion());
You are declaring argument for your function but not using them
Your function is
function conversion(a, b) { …
But you call the function without arguments conversion(), you could call it with arguments like this:
<input type="button" value="Click for Conversion" onclick="conversion(40,10) " />
You are overwriting your arguments without using them
But you will see that nothing changes by adding these numbers, it is because you overwrite them in your function anyway a = 10; b = hTemp. Also if you want to convert a temperature you only should have one input variable. So let us rewrite your function:
function conversion(cTemp) {
let hTemp = ((cTemp * 9))/5 + 32;
alert (hTemp);
}
So now then function accepts an argument called cTemp and then puts out the conversion. You can now call the function with different arguments like this:
<input type="button" value="Click to convert 40 C" onclick="conversion(40) " />
<input type="button" value="Click to convert 50 C" onclick="conversion(50) " />
Or even better, you can do a prompt:
function promptForConversion() {
let cTemp = prompt("Temperature in Celsius");
conversion(cTemp);
}
<input type="button" value="Click to convert number" onclick="promptForConversion(50) " />
These are very basic principles, I highly recommend to do some more tutorials, that also teach you how to organize your code in reusable functions. Good luck!
Related
It's my first time coding with Javascript, and I am not sure how to proceed with fixing this code. I have tried basic stuff like checking variables are named correctly. I am unsure with what steps to take to fix this code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Convert Fahrenheit to Centigrade</title>
</head>
<body>
<h1>Convert Fahrenheit to Centigrade</h1>
<p>Enter degrees in Fahrenheit</p>
<input type="number" id="Fahrenheit">
<p>Degrees in Centigrade</p>
<input type="number" id="Centigrade">
<br /><br />
<button onclick="doCalculation()">Calculate Centigrade from Fahrenheit</button>
<p id="displayResult"></p>
<script>
var fahrenheit;
//var centigrade;
var convertedResult;
function calculateTemperature(fahrenheit)
{
var temperature = (fahrenheit - "32") * 5 / 9;
return temperature;
}
function doCalculation(){
fahrenheit = document.getElementById("Fahrenheit").value;
//centigrade = document.getElementById("Centrigrade").value;
convertedResult = calculateTemperature(fahrenheit)
document.getElementById("displayResult").innerHTML+= fahrenheit + "in Centigrade is" + temperature;
}
</script>
</body>
</html>
The variable temperature which you are using within the value which is getting printed is not defined. If you check the browser, console, you will be able to identify that error.
The value of the result is stored in the convertedResult variable. That variable should be used within the value which is getting printed instead of temperature
function doCalculation(){
fahrenheit = document.getElementById("Fahrenheit").value;
//centigrade = document.getElementById("Centrigrade").value;
convertedResult = calculateTemperature(fahrenheit)
document.getElementById("displayResult").innerHTML = fahrenheit + "in Centigrade is" + convertedResult;
}
So I'm doing this for a summer class and I have to get this carpet calculator to display the result in a "Perform a document.write to display the results on a new html page." (quote taken straight from assignment). It says to use document.write and I grasp the concept of document.write after using some tutorials on w3 but when I try to apply it to my project, it has no effect on my web page.
Below is my code:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<link rel="stylesheet" href="http://www.w3.org/StyleSheets/Core/Oldstyle" type="text/css" />
<head>
<title>Tutorial Project 10</title>
</head>
<body>
<h1>Carpet Calculator</h1>
<form name = "carpet" action=" ">
</br>Enter the length of your room in feet</br><input name = "length" type = "text" />
</br>Enter the width of your room in feet</br><input name = "width" type = "text" />
</br>Typically an allowance is made for room irregularities and unavoidable waste.
</br>Enter the percent overage as an integer in the interval [0, 20]</br><input name = "overage" type = "text" />
</br></br><input name = "SqFt" type = "button" value = "Compute Square Feet " onclick = "ComputeSquareFeet()" />
</br></br><input name = "SqYd" type = "button" value = "Compute Square Yards" onclick = "ComputeSquareYards()" />
</br></br><input type = "reset" value = "Clear" />
</form>
<script type="text/javascript">
function ComputeSquareFeet()
{
var SqFt = (carpet.length.value*carpet.width.value);
carpet.SqFtResult.value = SqFt+(SqFt*(carpet.overage.value / 100));
document.write(SqFtResult);
}
function ComputeSquareYards()
{
var SqYd = ((carpet.length.value/3)*(carpet.width.value/3));
carpet.SqYdResult.value = SqYd+(SqYd*(carpet.overage.value / 100));
document.write(SqYdResult);
}
</script>
</body>
</html>
The page works like this, the user enters data into 3 boxes, the button is pressed which calls the function and at the end of that function, it performs document.write. However, after doing a bunch of trial and error, I concluded that my formulas were working and the function was being called but the document.write wasn't for some reason.
Any ideas on what I'm doing wrong? Thank you!
Edit: I had a text box that displayed the result of the function just to make sure it was working but once I switched to document.write, nothing seemed to work
Seems like you need to write this to a new HTML page; for example try calling the below function with your text:
function writeToNewPage(text) {
var newPage = window.open("", "New Page","width=400, height=300, scrollbars=1, resizable=1");
newPage.document.open();
newPage.document.write(text);
newPage.document.close();
}
You can't use document.write on the current page without wiping the whole page, and it seems the assignment question does actually say a new page.
It seems to me that the problem there is not really the document.write, but probably the way you are getting the data from the form.
It should be something like:
document.forms["formname"][fieldname].value;
Also to create a variabe do it like:
var SqYdResult=somthing;
Hope it helps
Turns out I was getting ahead of myself
function ComputeSquareFeet()
{
var SqFt = (carpet.length.value*carpet.width.value);
carpet.SqFtResult.value = SqFt+(SqFt*(carpet.overage.value / 100));
document.write(SqFtResult);
}
needs to be
function ComputeSquareFeet()
{
var SqFt = (carpet.length.value*carpet.width.value);
var SqFtResult = SqFt+(SqFt*(carpet.overage.value / 100));
document.write("Carpet needed in square feet: " + SqFtResult);
}
Because I wasn't declaring the variable it wasn't working. When I defined it I got the result I wanted.
Thank you all for your help!
Hey guys I am trying to create a JavaScipt function that when called will print the value created by the claclBMI() function. I feel that having the first function do the calculations for the BMI is correct. Is there anyway to make the button print the result of the calcBMI function?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Body Mass Index</title>
</head>
<body>
<table width="80%" border="0">
<tr>
<th>Weight in Pounds</th>
<th>Height in Inches</th>
<th>Body Mass Index</th>
</tr>
<tr>
<td><input id="box1" oninput="number" type="text" /></td>
<td><input id="box2" oninput="number" type="text" /></td>
<td><button onclick="printBMI()">Calculate BMI</button></td>
</tr>
</table>
<p id="calcBMI"></p>
<script>
function calcBMI()
{
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
var BMI = document.getElementById('BMI');
var myResult = (myBox1 * 703) / (myBox2 * myBox2);
BMI.value = "parseInt(myResult)";
}
function printBMI()
{
document.write (myResult);
}
</script>
</body>
</html>
Some comments:
calcBMI is not returning any value
document.getElementById('BMI'); finds nothing, since there is no element with id BMI
BMI.value explodes, since BMI is undefined
parseInt(someStringWithDigits) without quotes is a function, but what you have there is just a string, that does nothing
You use document.write(myResult), but the function printBMI can't see variables declared inside on the other function.
¿Is this some sort of assignment? If so, it would be nice to know what knowledge is expected for you to apply.
In order to solve some of your issues:
document.getElementById('box1'); will give you the first input
calcBMI should return the value, unless you have a good reason to assign the result somewhere else, but from my perspective, it seems better to just return the value and make no other collateral effects.
Once you do that, document.write(calcBMI()) will erase everithing from your page and put the result instead. You probably want to put the result somewhere specific, but I suppose it's a good start.
You need to parseInt() before trying to run calculations on them, if they are retrieved as a string:
function calcBMI() {
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
var BMI = document.getElementById('BMI');
var myResult = (parseInt(myBox1) * 703) / (parseInt(myBox2) * parseInt(myBox2));
BMI.value = myResult;
}
Also if you want the result to be on the text of the button it would be:
BMI.innerHTML = myResult;
Also, when you call the printBMI() function document.write() erases everything on the page, I think, and replaces it with your value.
I want to write a script that multiplies any number in a text field with itself by the push of a button and gives the result as an alert.
I'm completely new to Javascript (and have to write my first exam later today).
The syntax is killing me, sometimes so similar to Java, but than again not.
Here's what I came up with so far:
<!DOCTYPE html>
<html>
<head>
<script>
function myMultiply()
{
var x= $('#num1').val();
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1">
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
You'll want to make sure you parse the input value as it will be a string when you query for it. To operate on it using multiplication, you need a number. You'll usually want to pass 10 as the second radix parameter as there are different implementations of parseInt
function myMultiply() {
var x = parseInt($('#num1').val(), 10);
var y = x*x;
alert(x + " times " + x + " equals " + y);
return false;
}
You cant multiply string it will be concatenated, parse value to int using parseInt first
parseInt
function myMultiply()
{
var x= parseInt($('#num1').val(), 10);
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
try replacing var y=x*x; with var y=Number(x)*Number(x);
Along with other answers indicating you should parseInt it should be noted that you aren't currently including jQuery (which gives you access to the $(".element") notation).
jQuery is a very common javascript library that saves a lot of time for very common Javascript tasks (selectors, events etc). You'll see the $() notation in many tutorials and to use it you need to include jQuery.
This will work:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function myMultiply()
{
var x= parseInt( $('#num1').val(), 10 );
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1" />
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
Your code is fine. You are simply missing the jquery include.
Add <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> right above your other script and everything works unchanged.
Javascript will parse strings and convert them to numbers automatically when it sees that you are trying to multiply. "4" * "2" is 8, not "44" or "42" or any other magical combination. You have a syntax error by referring to $ without actually including jQuery as a required script, so the function ends up being undefined.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function myMultiply()
{
var x= $('#num1').val();
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1">
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
My html page displays a button that calls a function when it is clicked. I checked to make sure that the button works properly by displaying a message when clicked and it worked. I created this function to change the global varible but when I click another button on my html page to show the value of the varibles the varibles have not changed to the value I set them using my function. Could someone find the problem in my code below?
var a = 5;
var b = 16;
var c = 27;
function reset(){
a = 0;
b = 0;
c = 0;
}
My html code to call the function:
<!DOCTYPE HTML>
<html>
<center>
<script type="text/javascript" src="game.js" > </script>
<form>
<input type="button" value="Reset Variables" style="width:250px;height:50px" onclick="reset()" >
</form>
</html>
Javascript code to show the variables:
function display(){
document.write("A is equal to " + a + "<br/>");
document.write("B is equal to " + b + "<br/>");
document.write("C is equal to " + c );
}
Html to display the variables
<!DOCTYPE HTML>
<html>
<center>
<script type="text/javascript" src="game.js" > </script>
<form>
<input type="button" value="Show Variables" style="width:250px;height:50px" onclick="display()" >
</form>
</html>
change the function name to reset_vars or anything else. reset() is in-built DOM function used for resetting forms.
http://www.w3schools.com/jsref/met_form_reset.asp
There won't be any conflict when a global variable is used inside a function unless a local variable is defined. in such case, use window.variable_name to access global variable.
That can`t work, because you are asserting that variables in function scope. But your variables are currently stored in global scope (window), so this code will work:
var a = 5;
function reset() {
console.log(window.a); // 5
window.a = 10;
}
reset();
console.log(a); // 10