new to HTML5 in general so sorry if this is an easy fix :)
I have this HTML file that takes 4 user inputs (integers) and times them by 4 other variables, then adds up the new variables and outputs it into a HTML via document.getElementById("out").innerHTML When I run the HTML in chrome it does nothing at all, and I dont know why, Adobe Dreamweaver is not flagging up any errors at all and it runs fine in browser as far as I can tell.
If you do fix it would you please try and explain what you are doing and why it works and try to keep my code in its form so I can still understand it (hopefully that made sense?)
Here is my code in its entirety-
<!doctype html>
<html>
<body>
<h1><font face="arial">How much space do you need?</font></h1>
<h2><font face="arial">Number of Files: </font></h2>
<form id="filenum">
<font face="arial"> Documents: <input type="int" name="doc" value="0"><br></font>
<font face="arial"> Photos: <input type="int" name="photo" value="0"><br></font>
<font face="arial"> Music: <input type="int" name="music" value="0"><br> </font>
<font face="arial"> Films: <input type="int" name="film" value="0"><br></font>
</form>
<button onclick="outputsize()">Calculate</button>
<script>
var doc,photo,music,film,ttb,tgb,tmb,tdoc,tphoto,tmusic,tfilm,files,sdoc,sphoto,smusic,sfilm;
function outputsize() {
sdoc=0.1
sphoto=8
smusic=5
sfilm=1400
files=document.getElementById("filenum");
doc=x.elements["doc"].value;
photo=x.elements["photo"].value;
music=x.elements["music"].value;
film=x.elements["film"].value;
tdoc=doc*sdoc;
tphoto=photo*sphoto;
tmusic=music*smusic;
tfilm=film*sfilm;
tmb=tdoc + tphoto + tmusic + tfilm;
tgb=tmb/1000;
ttb=tgb/1000;
document.getElementById("out").innerHTML="You need a, "+tmb+"MB or bigger hard drive.<br>";
document.getElementById("out").innerHTML+="Or...<br>";
document.getElementById("out").innerHTML+="You need a, "+tgb+"GB or bigger hard drive.<br>";
document.getElementById("out").innerHTML+="Or...<br>";
document.getElementById("out").innerHTML+="You need a, "+ttb+"TB or bigger hard drive.<br>";
}
</script>
<p id="out"><font face="arial">We calculated:</font></p>
</body>
</html>
Again, sorry if this is a stupid question (if such a thing exists) but I have been at this for hours and can't solve it :(
This should work correctly. You were trying to get values from the form, but you were trying to obtain them from a variable that did not exist.
<h1><font face="arial">How much space do you need?</font></h1>
<h2><font face="arial">Number of Files: </font></h2>
<form id="filenum">
<font face="arial"> Documents: <input type="int" name="doc" value="0"><br></font>
<font face="arial"> Photos: <input type="int" name="photo" value="0"><br></font>
<font face="arial"> Music: <input type="int" name="music" value="0"><br> </font>
<font face="arial"> Films: <input type="int" name="film" value="0"><br></font>
</form>
<button onclick="outputsize()">Calculate</button>
<script>
var doc, photo, music, film, ttb, tgb, tmb, tdoc, tphoto, tmusic, tfilm, files, sdoc, sphoto, smusic, sfilm;
function outputsize() {
sdoc = 0.1;
sphoto = 8;
smusic = 5;
sfilm = 1400;
files = document.getElementById("filenum");
doc = files.elements["doc"].value;
photo = files.elements["photo"].value;
music = files.elements["music"].value;
film = files.elements["film"].value;
tdoc = doc * sdoc;
tphoto = photo * sphoto;
tmusic = music * smusic;
tfilm = film * sfilm;
tmb = tdoc + tphoto + tmusic + tfilm;
tgb = tmb / 1000;
ttb = tgb / 1000;
document.getElementById("out").innerHTML = "You need a, " + tmb + "MB or bigger hard drive.<br>";
document.getElementById("out").innerHTML += "Or...<br>";
document.getElementById("out").innerHTML += "You need a, " + tgb + "GB or bigger hard drive.<br>";
document.getElementById("out").innerHTML += "Or...<br>";
document.getElementById("out").innerHTML += "You need a, " + ttb + "TB or bigger hard drive.<br>";
}
</script>
<p id="out"><font face="arial">We calculated:</font>
</p>
You need to modify the function (replace 'x' with 'files'):
function outputsize() {
...
doc=files.elements["doc"].value;
photo=files.elements["photo"].value;
music=files.elements["music"].value;
film=files.elements["film"].value;
...
}
How to troubleshoot errors like these:
To figure this out, I pressed F12 in Firefox (also works in Chrome) to bring up the console. It showed an undefined variable called 'x' and told me the line where it should be changed.
You need to change x to files:
doc=files.elements["doc"].value;
photo=files.elements["photo"].value;
music=files.elements["music"].value;
film=files.elements["film"].value;
You never defined x so x was undefined. You did however define files which is what you want to use. You were trying to access elements of your form which you stored your form in the files variable not x.
Related
I'm working on a HTML/JS method of capturing data within multiple input text boxes and running into a strange issue when trying to retrieve the values held within the inputs. I'll go ahead and post the code here before explaining my issue.
<div class="card-body">
<div id="manual-record-headers">
<b class="manual-record-header">Serial Number</b>
<b class="manual-record-header">Drive Health</b>
<b class="manual-record-header">Location</b>
<b class="manual-record-header">Username</b>
</div>
<div id="manual-record-table">
<div class="manual-record-row" id="manual-row-1">
<input type="text" class="form-control manual-record-input serial-num-input" placeholder="Serial number for drive...">
<input type="text" class="form-control manual-record-input drive-health-input" placeholder="Drive health state...">
<input type="text" class="form-control manual-record-input drive-location-input" onsubmit="return false;" placeholder="Storage location for drive...">
<input type="text" class="form-control manual-record-input username-input" placeholder="Check in username...">
<button class="delete-row"> <img src="/static/main/img/delete.png" width="34" height="34" /> </button>
</div>
</div>
</div>
for ( x=1; x < manual_record_count + 1; x++ ) {
temp_inventory_list = []
try {
serial = $('#manual-row-' + x + ' > .serial-num-input').val();
health = $('#manual-row-' + x + ' > .drive-health-input').val();
location = $('#manual-row-' + x + ' > .drive-location-input').val();
username = $('#manual-row-' + x + ' > .username-input').val();
}
catch(err) {
alert(err.message);
}
[program, drive_type, product_type] = get_data_from_drive_serial(serial)
temp_inventory_list = [serial, health, location, username, program, drive_type, product_type];
inventory_list.push(temp_inventory_list);
}
For some reason, on the third text input, where I am trying to retrieve the value of the ".drive-location-input", the page is being submitted with the value from that text input. So if I was to input a value of "333333333" into the .drive-location-input text input, the page would go from 127.0.0.1/main to 127.0.0.1/main/333333333. I should also note, that the page gets redirected/submitted before the try/catch and alert ever go off, so I can't see any possible errors that would be causing this.
As far as I can tell, there is no reason why this should be occurring, especially since the other 3 text inputs seem to be able to be retrieved with no issue. Is this an issue with the one text input itself, or should I be looking into why the page is even submitting with the value obtained in the first place?
Please let me know if any other info is necessary, and thanks in advance for any help.
Turns out that using "location" as a variable name is a big no-no. "location" returns the window elements location, and apparently results in a page redirect. So for anyone else that may see this issue in the future, look into if any variable names you are using have conflicts... Not a fun way to waste half a day!
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;
I am currently creating a program that can calculate bmi with javascript. I am not sure why but it is not working properly. I must be missing something but I am not sure what it is. If someone could help me I would really appreciate it. Thank you.
<!DOCTYPE html>
<!-- -->
<html>
<head>
<meta charset="UTF-8" />
<title>Body Mass Index</title>
</head>
<BODY>
<header><img src="bmi.jpeg" width="380" height="132" border="0" alt="bmi"></header>
<video controls="controls"
width="320px" height="260px">
<source src="bmi.mp4"/>
<p>When it comes to weight loss, there's no lack of fad diets promising fast results. But such diets limit your nutritional intake, can be unhealthy, and tend to fail in the long run.</p>
<p>The key to achieving and maintaining a healthy weight isn't about short-term dietary changes. It's about a lifestyle that includes healthy eating, regular physical activity, and balancing the number of calories you consume with the number of calories your body uses.</p>
<p>BMI is a number calculated from a person's weight and height. BMI provides a reliable indicator of body fatness for most people and is used to screen for weight categories that may lead to health problems.</p>
<p>The BMI ranges are based on the relationship between body weight and disease and death.
Overweight and obese individuals are at increased risk for many diseases and health conditions, including the following:</p>
You need a flash player to view this video.
</video>
<ul>
<li>Hypertension</li>
<li>Dyslipidemia (for example, high LDL cholesterol, low HDL cholesterol, or high levels of triglycerides)</li>
<li>Type 2 diabetes</li>
<li>Coronary heart disease</li>
<li>Stroke</li>
<li>Gallbladder disease</li>
<li>Osteoarthritis</li>
<li>Sleep apnea and respiratory problems</li>
<li>Some cancers (endometrial, breast, and colon)</li>
</ul>
<script type="text/javascript">
function CalculateBMI(){
var inch=12;
var ft;
var bmi= Math.write(weight*703)/ (inch height)^2;
if(bmi<=19)
{"Underweight";
}
if else(19<bmi<=25)
{"Desirable";
}
if else(25<bmi<=29)
{"Prone to health risks";
}
if else (29<bmi<=40)
{"obese"
}
else(40<bmi)
{"Extremely Obese"
}
}
</script>
<form name="bmi">
<p> Weight:<p/></td> <td><input type="text" id="weight" name="weight" size="25" />
<p>Height:</p> <input type="text" id="textbox" name="textbox" size="25" /><td><p>Ft.</p><input type="text" id="textbox" name="textbox" size="25" /> <p>In.</p>
<input type="submit" id="Calculate BMI" name="Calculate BMI" value="Calculate BMI" size="25" onclick="CalculateBMI()" />
According to the Panel on
Energy, Obesity, and Body Weigth Standards published by
American Journal of Clinical Nurttrition, your category is:
<input type="text" id="textbox" name="textbox" size="25" />
</form>
</BODY>
</html>
I see a few things that are likely causing your issue. Lets start with this statement:
var bmi= Math.write(weight*703)/(inch height)^2;
You are not defining weight or height (you have to tell it to look in the textbox or send it to the function it does not automatically know you are referring to a textbox). I would expect something like
var weight = document.getElementById('weight').value;
There is no Symbol between height and weight, which is throwing a syntax error, you need to do something with these if they are going to be together (and do realize this is not adding the inches just calculating the feet in inches).
var bmi= (weight*703)/(inch*height)^2;
After that you are using if else - which is not valid in Javascript you would want to say:
else if (19<bmi<=25)
Lastly you are not returning a value nor specifying WHERE the value should go.
var results;
if (bmi<=19)
{
results = "Underweight"
}
document.getElementById('results').value = results;
Try implementing some of these suggestions and see if that gets you on the right track.
Your javascript had several systemic errors
for example 1<a<12 is not valid, it should be written a>1 && a<12
also, your CalculateBMI function had no idea what weight height in inches or height in feet where. You can include JQuery to make this easier but document.getElementById also works. To accomplish this I also gave meaningful names to your form variables.
You were not displaying the resulting string anywhere. Using getElementById you can also find the result element in your html and set its value to the result of the calculation.
If you don't want the page to refresh when you submit you have to set your form to receive a false value onsubmit.
Your math syntax for the bmi was off, I'm assuming it should be (703 * weight ) (height)^2 where height is in inches (after the foot and inch height variables have been combined).
The cleaned up Javascript should look like this. Note that this is probably not the best way to go about solving this problem.
edit: I think your BMI calculation was off as well. If the input weight and height are imperial (ie inch and lbs) then the inches should be multiplied by 0.025 to get meters and lbs should be multiplied by 0.45 to get kgs.
bmi= (weight_e* 0.45) / (((12*heightf_e)+heighti_e) * 0.025)^2;
function CalculateBMI(){
// To avoid erros due to hoisting define all
// of your vars at the top of your function
var ft,
bmi,
heighti_e, // height in inches
heightf_e, // height in feat
weight_e,
bmi_e, // the bmi element
bmi;
// Use getElementById to get a reference for the
// elements you will be using in your function
heighti_e=document.getElementById("heighti");
heightf_e=document.getElementById("heightf");
weight_e=document.getElementById("weight");
bmi_e=document.getElementById("bmi");
// Not all of these parenthesis are necessary but it
// helps to clear up the order of operation and avoid
// silly mistakes in long equations that are not
// broken up into several lines
bmi= (weight_e* 0.45) / (((12*heightf_e)+heighti_e) * 0.025)^2;
// set bmi to a string value
if(bmi<=19)
{
bmi="Underweight";
}
else if(bmi>19 && bmi<=25)
{
bmi="Desirable";
}
else if(bmi>25 && bmi<=29)
{
bmi="Prone to health risks";
}
else if (bmi>29 && bmi<=40)
{
bmi="obese";
}
else(bmi>40)
{
bmi="Extremely Obese";
}
bmi_e.value=bmi; // bmi_a is the reference to the
// element in your form with the
// bmi id
return false; // make sure you return false to prevent
// page reload
}
I have not cleaned up your HTML form, but at least it now works. I have moved the submission action from the button to the form tag. I have also given the height weight and bmi inputs meaningful id names so we can reference them in the CalculateBMI function.
<form action="" name="bmi" onsubmit="return CalculateBMI()">
<p> Weight:<p/></td> <td><input type="text" id="weight" name="weight" size="25" />
<p>Height:</p> <input type="text" id="heightf" name="textbox" size="25" /><td><p>Ft.</p><input type="text" id="heighti" name="textbox" size="25" /> <p>In.</p>
<input type="submit" id="Calculate BMI" name="Calculate BMI" value="Calculate BMI" size="25" />
According to the Panel on
Energy, Obesity, and Body Weigth Standards published by
American Journal of Clinical Nurttrition, your category is:
<input type="text" id="bmi" name="textbox" size="25" />
</form>
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.
I'm doing this for a class. The point is to show how to boil water in programming... idk it's weird but you can look at my code and see what's up. It has a purpose but I don't have time to explain. please don't make any big changes. I want it to run the way it is not how it should be done or whatever. I'm not the best with javascript so please don't judge as much.
issue
it the first input works fine so no worries about that. It's my form that has issues.... what's supposed to happen is I type one of the variables in and it'll display what ever pour says. But when I go to submit it doesn't work whatsoever... just restarts the page! I give so far.... because I obviously don't know what's wrong :P something stupid probably. Thanks!
code
<html>
<head>
<title>
Boiling Water
</title>
</head>
<body bgcolor='#000000'>
<center>
<font color='#ffffff' size='8'><b>D.W.B.A</b>
<br>
Digital</font> <font color='#00ffff' size='8'>Water</font><font color='#ffffff' size='8'> Boiling Association</font>
<br>
<font size='3' color='#ffffff'>Programmed in JavaScript</font>
<br>
<br>
<br>
<p><font color='#ffffff' size='4'>Grab 1 of 56 Cups From the Kitchen Cabinet!</font></p>
<font color='#ff0000' size='4'><p id="cup"><input type='button' value='Obtain Cup' onclick='cup()' /></p></font>
<script>
function cup() {
var cabinet=56;
var quantity=55;
var obtain=cabinet-quantity;
var cupP=document.getElementById("cup")
cupP.innerHTML="You have Obtained " + obtain + " Cup";
}
</script>
<script>
function fill() {
var x=document.getElementById("calculate").value;
var optionzero=0;
var optionone=25;
var optiontwo=50;
var optionthree=75;
var optionfour=100;
if (optionzero) {
pour="Please Pour contents into your Cup";
} else if (optionone) {
pour="You have filled the Cup 1/4 of the way with water";
} else if (optiontwo) {
pour="You have filled the Cup 2/4 or 1/2 of the way with water";
} else if (optionthree) {
pour="You have filled the cup 3/4 of the way with water";
} else if (optionfour) {
pour="Your cup is filled (4/4 of the way) with water";
}
document.getElementById("fillup").innerHTML=pour;
}
</script>
<br>
<form type='input' >
<font color='#ffffff' size='4'>Fill the Cup with Water per 25% out of 100% Ex) 25%, 75%, etc. </font>
<br>
<br>
<input type='text' id='calculate'>
<br>
</form>
<input type='submit' value='Calculate' onclick='fill()' />
<br>
<font color='#ffffff'><p id='fillup'>
</p></font>
</center>
</body>
</html>
Simply try not submitting the form. You can either return false; from the fill function and change your inline handler to onclick='return fill()' or simply change the whole input for:
<button type='button' onclick='fill()'>Calculate</button>
Submitting the form is mostly useful when you want to send information to a server-side process which you don't need to do there.
Your form is submitting to the current page. You should probably move your fill() to onsubmit for the form. Also, make sure that function returns false, or the form will still submit.