Make a JavaScript button print a value - javascript

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.

Related

Debugging a Celsius to Fahrenheit Challenge

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!

GetDistance Javascript not returning nothing whilst having some values for as parameters

I am trying to get a result from this function. However, nothing is being returned onto my page, just "This example calls a function which performs a calculation, and returns the result:". I need this function to get every postcode in the database from the properties tables and find the distance. Also, one postcode is set always going to be the same so I need to set that and the other postcode is going to be a postcode from the properties table.
<?php
include ("../connect.php");
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<script type="text/javascript">
var x = getDistance(52.482799000000000, -2.000643000000000, 52.48463500000000, -1.980759000000000);
function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {
$earth_radius = 6371;
$postLat = deg2rad($latitude2 - $latitude1);
$postLon = deg2rad($longitude2 - $longitude1);
$a = sin($postLat/2) * sin($postLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($postLon/2) * sin($postLon/2);
$c = 2 * asin(sqrt($a));
$d = $earth_radius * $c;
//$distance_miles = $km * 0.621371; //distance in miles
return $d;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Where are you using the x variable?
I would expect something like this:
<p>This example calls a function which performs a calculation, and returns the result:
<div id="result">
</div>
</p>
var x = getDistance(52.482799000000000, -2.000643000000000, 52.48463500000000, -1.980759000000000);
$('#result').text(x);

I want to get two integers from a user via a text input, find the difference between the two numbers and divide that number by 25. How do I do this?

I'm making a small website as a test. Very new to JavaScript and HTML forms so I thought i'd throw myself into what I consider to be the deep end and give it a go.
I'm trying to get an interger to be displayed on the page, that is the result of a few calculations.
I want to find the difference between the first number (current value), and the second number (desired value) and then divide that number by 25 and store that as a variable. I then want to display that variable inside a message.
My current HTML :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<form>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<input type="submit" onclick="calculate()">
</form>
<script src="js/main.js"></script>
</body>
</html>
My current JavaScript :
function calculate() {
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
var difference = desiredRating - currentRating;
var gamesToPlay = difference / 25;
document.write("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
You are 99% there. All you have to do is change
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
into
var currentRating = parseInt(document.getElementById("currentRating").value);
var desiredRating = parseInt(document.getElementById("desiredRating").value);
The way you had it, those variables just held the HTML (technically, DOM) elements themselves, and not the values that were in them. This gets the values and then turns them into integers so you can do math with them. If you do this, your site do exactly what you want it to do.
Be careful:
var currentRating = document.getElementById("currentRating").value;
is a String (text) value... to be sure of int value you can do
try{
var currentRatingInt = parseInt(currentRating);
}catch(e){
alert(currentRating + " is not an integer");
}
If you like to display result in page you can use a DIV with and id and do:
document.getElementById("idOfYourDiv").innerHTML = "What you like to display in div";
hope this code will help :
html :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<div>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<button onclick="calculate();">Calculate</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
javascript :
function calculate() {
var currentRating = document.getElementById("currentRating").value;
var desiredRating = document.getElementById("desiredRating").value;
var gamesToPlay = (desiredRating - currentRating) / 25;
gamesToPlay = Math.abs( parseInt(gamesToPlay) );
alert("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
Subtract first field from the other, and if the value is not greater than 0 multiply by -1.
Divide that by 25.

HTML + Javascript document.write not working

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!

html script variable assignment

So I have a script block:
<script>
var totalPopulation = 0;
for(xxxxx){
totalPopulation = totalPopulation + xxx
}
</script>
<tr>
<input type="text" name="censusPop" value=totalPopulation/>
<tr>
I'm still quite green to javascript. But is there a way to assign the value of a variable in a script block to a HTML element like input type? I know that the code is unreachable.
hope it will help you to understand how javascript work
<html>
<head>
<script>
var totalPopulation = 0;
function addAndShowPopulation(population) {
totalPopulation = totalPopulation + population;
var input_tag = getTag('my_input_id');
input_tag.value = totalPopulation;
}
function startAdding() {
addAndShowPopulation(10);
setTimeout( function(){startAdding();},1000);
}
function getTag(id) {
return document.getElementById(id);
}
</script>
</head>
<body onload="startAdding();">
<div>
<input type="text" id="my_input_id" name="censusPop" value="" placeholder="Total Population"/>
</div>
</body>
</html>
Yes, you just have to give an id to the input, for instance "id = my_input_id";
Then, in the javascript, just write :
$("my_input_id").value=totalPopulation;
That's how ajax works: find html elements ids and fill them dinamically using javascript values.
Just be carefull that the html in read before the JS. If not, $("my_input_id") will return Null
More so, you need to do something like this:
<tr>
<td>
<input type="text" id="censusPop" name="censusPop" value=""/>
<td>
<tr>
<!-- Other stuff -->
<script>
var totalPopulation = 10;
// or for loop, or whatever here.
var censusText = document.getElementById('censusPop');
censusText.value = totalPopulation;
</script>
</body>
HTML and JavaScript can interact, but not directly like that. The best thing to do is use <script> tags to setup code that updates the browser DOM. By putting the <script> tags after the HTML, usually at the bottom of the <body> tag, you allow the browser a chance to create the elements before you actually try to use them.
Another note: <tr> tags should contain <td> tags, it's the difference between a row and a column.
If you need to do multiple DOM manipulations, I'd suggest using jQuery is the proper way.
<tr>
<input id="censusPop" type="text" name"censusPop" value=""/>
</tr>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
// make sure, the code is executed when the DOM is ready
$(function () {
// grab the input element by its ID
var $input = $('#censusPop'),
totalPopulation = 0;
// do your population calculations
totalPopulation = ....;
// assign the value to the input element
$input.val(totalPopulation);
});
</script>

Categories