How to create a function call in javascript with xhtml? - javascript

Here is the code that i have so far I am having trouble getting the code to execute the function and properly output the data from the function to the "Total BMI" text box I have been searching for hours on this trying to figure it out. this is a class assignment I am having trouble with it because I am not understanding the syntax used in javascript to do everything that I need done. My teacher is literally of no help as this is our second assignment and has never had a lecture on how to even begin writing code in Javascript. Thanks for any help that anyone may provide.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 Strict//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>BMI Calculator</title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
<link rel="stylesheet" href="BMI.css" type="text/css" />
<script type="text/javascript">
/* <![CDATA[ */
function calcBMI(Height, Weight) {
var h = parseInt(height);s
var w = parseInt(Wieght);
var TotalBMI = w * 703 / (h * h);
document.write ("Your BMI is: " + TotalBMI)
}
/* ]]> */
</script>
</head>
<body>
<h2>BMI Calculator</h2>
<form action="" name="BMI">
<table border="1">
<tr><td>Height :(in)</td><td><input type="text" name="Height" value="" /></td></tr>
<tr><td>Weight :(lbs)</td><td><input type="text" name="Weight" value="" /></td></tr>
<tr><td><input type = "button" value = "Calculate" onclick = "calcBMI('Height', 'Weight')"></td></tr>
<tr><td>Total BMI:</td><td><input type="text" name="TotalBMI" value="" /></td></tr>
</table>
</form>
</body>
</html>

Here,
onclick = "calcBMI('Height', 'Weight')"
you're passing the strings 'Height' and 'Weight', although you mean to pass the values of the related fields. Forms don't work that way, so instead you should get rid of the parameters altogether,
onclick = "calcBMI()"
and in the function, use DOM traversal to get the values you need. First, add some id attributes to the fields you're interested in, e.g.
<tr><td>Height :(in)</td><td><input type="text" name="Height" value="" id="height" /></td></tr>
<tr><td>Weight :(lbs)</td><td><input type="text" name="Weight" value="" id="width" /></td></tr>
then get their value like so:
function calcBMI() {
var h = parseInt(document.getElementById('height').value);
var w = parseInt(document.getElementById('weight').value);
var TotalBMI = w * 703 / (h * h);
document.write ("Your BMI is: " + TotalBMI)
}

First lets look at this:
onclick = "calcBMI('Height', 'Weight')"
Your passing strings here, in which can't convert to be an integer (at least not the type your expecting). It appears you want to get the values of your elements with the names Height and Width. Well this is a good use of id's other than name's.
<tr><td>Height :(in)</td><td><input type="text" id="Height" value="" /></td></tr>
<tr><td>Weight :(lbs)</td><td><input type="text" id="Weight" value="" /></td></tr>
...
<tr><td>Total BMI:</td><td><input type="text" id="TotalBMI" value="" /></td></tr>
Now don't need any parameters for the calcBMI() functions because we can get them directly like so:
document.getElementById("Height").value;
So here are the changes to your function:
function calcBMI() {
var h = parseInt(document.getElementById("Height").value);
var w = parseInt(document.getElementById("Weight").value);
var TotalBMI = w * 703 / (h * h);
document.getElementById("TotalBMI").value = "Your BMI is: " + TotalBMI;
}
Note I changed the document.write() to .innerHTML. Because running document.write() after the page loads rewrites the DOM.
Also note that submitting the <form> will refresh your page. It does not appear you really need the <form>, so I recommend just removing it. Either that or prevent the default page refresh behavior.

Related

I get NaN error when trying to create a basic calculator

I'm 3 days into learning Javascript and im really excited to understand more of this language, before i started i've done a basic HTML & CSS education. I'm currently on a 2 year program in a University in Sweden.
I'm trying to create a very basic calculator, that for now only adds 2 numbers together. I have 1 box, and another box. I want to make that each number written in each of these boxes is displayed as the total of box1, box2 in the third and final box.
At this moment i get "NaN" in the 3rd box when trying to add 2+3.
As i said, I'm really new and i appreciate all help i can get, and note that im not here for anyone to do my assignments which we have plenty of, i am really interessted in learning and understanding the language because i would like to work with this later in life when im done with my education.
Cheers!
<h1>Addera två tal med varandra</h1>
<form>
<input type="text" value="0" id="tal1" /> <br>
<input type="text" value="0" id="tal2" /> <br>
<input type="button" value="Beräkna" onClick="kalkylera();" />
<p>Den totala summan är</p>
<input type="text" value="0" id="svar" />
</form>
<script>
function kalkylera() {
//Get the two numbers entered in the box
var ForstaTalet = document.getElementById("tal1").value;
var AndraTalet = document.getElementById("tal2").value;
//Count the two entered numbers together
var svar = tal1 + tal2;
//Show result
document.getElementById("svar").value = svar;
}
</script>
PS, I'm not sure why "//# sourceURL=pen.js" is written i the bottom of the calculator when adding this to the codepen, that is not how it looks when viewing it in chrome.
Thanks in advance.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form>
<input type="text" placeholder='num1' id="tal1"/> <br>
<input type="text" placeholder='num2' id="tal2"/> <br>
<input type="button" value="Add" onClick="sum()"/>
<input type="text" placeholder='sum' id="svar"/>
</form>
<script>
function sum()
{
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
var svar = ForstaTalet + AndraTalet;
document.getElementById("svar").value = svar;
}
</script>
</body>
</html>
This works fine.
You need to cast your values as float with parseFloat and use the right variables as in the following example:
//Get the two numbers entered in the box
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
//Count the two entered numbers together
var svar = ForstaTalet + AndraTalet;
//Show result
document.getElementById("svar").value = svar;

Trying to run a program that calculates the needed grade on a final exam to get their desired overall grade

I am trying to run a program that allows a user to input their current overall grade grade (f), their desired overall grade (dg), and the weight of their final exam (g), and would ideally return their needed grade on the final exam to achieve their desired grade.
I have the equation, but am not sure why it is not returning a result on the screen. Can anyone tell me why?
<!DOCTYPE html>
<html>
<title>ffdfsdfdsfdsf</title>
<head>
<script>
function blahBlah
() {
var f = document.getElementById ('f').value
var f = document.getElementById ('f').value
var f = document.getElementById ('f').value
var f = (f - f *(4 - f)) / f
}
</script>
</head>
<h1>
f</h1>
<body>
<p>fe: <input id="cg" min="1" max="120"
onchange="blahBlah"</p>
<p>f: <input id="dg" min="3" max="11"
onchange="cf"</p>
<p>f: <input id="wof" min="3" max="11"
onchange="f"</p>
<p><button>Submit</button></p>
<h2 id="f"></h2>
</body>
</html>
Like I said, ideally there are three forms. Once the user completes these inputs, a pop up of their needed grade on the final would pop up under the submit button.
You had some syntax errors which I have corrected in this snippet, namely you needed to make it a string when you were setting innerHTML (thought you should probably use innerText), your <input> tags weren't closed, and you need to invoke your function with () in your onchange attributes.
function computeGrade() {
var cg = document.getElementById("cg").value;
var dg = document.getElementById("dg").value;
var wof = document.getElementById("wof").value;
var ng = (dg - cg * (100 % -wof)) / wof;
document.getElementById("ng").innerHTML = "Needed_grade: " + ng + "%";
}
<h1> Class Calculator</h1>
<p>Current grade: <input id="cg" min="1" max="120"
onchange="computeGrade()"></input></p>
<p>Desired grade: <input id="dg" min="1" max="120"
onchange="computeGrade()"></input></p>
<p>Final weight: <input id="wof" min="1" max="100"
onchange="computeGrade()"</input></p>
<p><button>Submit</button></p>
<h2 id="ng"></h2>

How to use a function in an external Javascript file in HTML?

This is my first time using an external Javascript file. I am doing the exercise in the murach series of books on Javascript and I am stuck on some pretty basic things. I will show the Javascript coding i did then i will show you the html file. Whenever I click the button to calculate the future value it does nothing even though I have the onload event handler.
/*Javascript*/
var $ = function(id) {
return document.getElementById(id);
};
function calculateFV(investment, interest, years) {]{
investment = $("investment").parseFloat($("investment").value);
interest = $("annual_rate").parseFloat($("annual_rate").value);
years = $("years").parseInt($("years").value);
var cInterest = investment * interest;
cInterest = parseFloat(cInterest);
futureValue = parseFloat(futureValue);
for (var i = 1; i < years; i++) {
investment = investment + (cInterest / 100);
}
investment = parseFloat(investment).toFixed(2);
$ ("future_value") = investment;
}
window.onload = function() {
$("calculate").onclick = calculateFV;
$("investment").focus();
};
/* End of Javascript */
/* HTML */
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1>Future Value Calculator</h1>
<label for="investment">Total Investment:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="annual_rate">
<span id="rate_error"> </span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"> </span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
/* End of HTML */
Regardless of the typographic errors in your code, there are some other mistakes you do I would like to mention:
parseInt() is a function; not a method. Therefore it must be used as a function. Like so: investment = parseFloat($("investment").value);
instead of:investment = $("investment").parseFloat($("investment").value);
$("future_value") is the textbox; not it's value. To actually have something appear in $("future_value"), you have to say: $("future_value").value = investment.
Your calculateFV() function should not have any parameters. Investment, interest and years are local variables inside the function, so your function doesn't require any input.
You parse too much and carelessly. In your code you say: cInterest = parseFloat(cInterest); and futureValue = parseFloat(futureValue);• We use parseFloat() to parse a string. The above variables contain arithmetic values that occurred after a mathematical operation and not strings. Therefore you do not need to parse them.
I created a jsFiddle with your code corrected and properly functioning. You can find it here.
Good luck in your learning process ☺

html sending parameters to function from id

I'm an absolute beginner and tried to find similar questions but couldn't. Apologies if this has been answered previously.
In my assignment we need to create a form with 2 text fields and 1 button. The fields are for height and width and the idea is that onclick on the button will send the 2 parameters to a function that will change the height + width attributes for a photo. I know I'm doing something wrong because the picture simply disappears. Ideas? Thanks!
<html>
<head>
<script>
function borderResize(height1, width1)
{
document.getElementById('Amos').height = height1;
document.getElementById('Amos').width = width1;
}
</script>
</head>
<body>
<img src="Amos.jpg" id="Amos" />
<form>
<input type="text" id="height" placeholder="Height" />
<input type="text" id="width" placeholder="Width" />
<input type="button" value="click!" onclick="borderResize('height.value', 'width.value')"/>
</form>
</body>
</html>
When you write
onclick="borderResize('height.value', 'width.value')"
in means that on click borderResize function will be invoked with two string arguments, literally strings "height.value" and "width.value". In your case you want something like this
onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
In above case you are selecting element from DOM using getElementById method and then read its value property.
You should learn to use addEventListener(), I would recommend you not to use ugly inline click handler.
The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on.
Here is an example with your code.
window.onload = function() {
document.getElementById('button').addEventListener('click', borderResize, true);
}
function borderResize() {
document.getElementById('Amos').height = document.getElementById('height').value;
document.getElementById('Amos').width = document.getElementById('width').value;
}
<img src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/s200x200/11034289_10152822971918167_2916173497205137007_n.jpg?oh=71de7a46a75a946cf1d76e5ab10c1cdc&oe=55889977&__gda__=1434173455_6127f174627ed6014c84e562f47bc44c" id="Amos" />
<input type="text" id="height" placeholder="Height" />
<input type="text" id="width" placeholder="Width" />
<input type="button" id="button" value="click!" />
However as for your immediate problem you can use
onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
onclick="borderResize('height.value', 'width.value')"
here you pass to borderResize strings: 'height.value', 'width.value'.
You may get value of input from function:
function borderResize(height1, width1)
{
document.getElementById('Amos').height = document.getElementById('height').value;
document.getElementById('Amos').width = document.getElementById('width').value;
}

place value into input box from query string not working

how can I take the value of a query string and place it into an input box? Currently I have:
<input type="text" name="spouse" id="spouse" value="<script type="text/javascript">
document.write("Name: " + Request.QueryString("spouse"));
</script>"/>
But that only takes the script take and all of its contents and places it into the input box.
I would like to be able to take my query string that is coming from this code:
<tr >
<td><input type="text" name="n1" value="Duck, Donald" /></td>
<td><input type="text" name="n2" value="Daisy" /></td>
<td><input type="button" value="Show" title="Show"
onclick="location.href='example123.html?name=' + escape(this.form.n1.value)+ '&spouse=' + escape(this.form.n2.value);" />
</td>
and have the value for name or spouse appear inside of an input box. What is the proper way to place a value into an input box from a query string?
Request.QueryString is not a native JavaScript function. Use the document.location object and parse out the value you want.
Perhaps use the onload function to perform the action you need. This calls your function once the document has been fully loaded and so you know all tags in the html will exist at this point and be can be referenced properly.
eg.
<html>
<head>
<title>Value Setting</title>
<script type="text/javascript">
window.onload = (function() {
document.getElementById('spouse').value = "one way";
document.forms[0].elements[1].value = "another way";
/* note elements refers to only input children */
});
</script>
</head>
<body>
<form id="myform">
<div>
<input id="first-field" value="first-field" onchange="this.value += ' an example';"/>
</div>
<div>
<p>
<input id="spouse" value="spouse"/>
</p>
</div>
</form>
</body>
</html>
You can't embed elements in attributes as that isn't valid html. Though some attributes can get evaluated as javascript. Namely attributes such as action, onchange, onclick and so on.

Categories