lesterpierson123 lesterpierson123 - 29 days ago 17
HTML Question

Basic Temperature converter in HTML using Javascript functions

I'm having trouble getting this basic HTML temperature converter to work. Basically, the user enters in the box "tempinput" a temperature and selects either if the input is in C/F/K.

Once that's done, the user clicks on convert and the function convert() should run, displaying in the box "result" the temperature in the 2 other choices (So if C is selected, F and K would be displayed in the box).

Problem is, although it's a simple program and everything seems straightforward, it doesn't seem to be working. I've been trying to figure out what's not working to no avail.

Here's the code:



function convert() {
var temp = document.getElementById("initialtemp");
var valueSelected = temp.options[options.selectedIndex].value;

if (valueSelected == "c") {
var convertedF = cToF();
var convertedK = cToK();

return document.getElementById("result").innerHTML = convertedF + "F" + " = " + convertedK + "K";
} else if (valueSelected == "f") {
var convertedC = fToC();
var convertedK = fToK();

return document.getElementById("result").innerHTML = convertedC + "C" + " = " + convertedK + "K";
} else if (valueSelected == "k") {
var convertedF = kToF();
var convertedC = kToC();

return document.getElementById("result").innerHTML = convertedF + "F" + " = " + convertedC + "C";
}
}
// celcius to rest

function cToF() {
var c = document.getElementById("tempinput").value;
return (c * 9 / 5) + 32;
}

function cToK() {
var c = document.getElementById("tempinput").value;
return c + 273.15;
}
// fahrenheit to rest

function fToC() {
var f = document.getElementById("tempinput").value;
return (f - 32) * 5 / 9;
}

function fToK() {
var f = document.getElementById("tempinput").value;
return (f - 32) * 5 / 9 + 273.15;
}
// kelvin to rest

function kToC() {
var k = document.getElementById("tempinput").value;
return k - 273.15;
}

function kToF() {
var k = document.getElementById("tempinput").value;
return (k - 273.15) * 9 / 5 + 32;
}

<h1>Temperature Converter</h1>
<div>
<h2>Celcius: "C" Fahrenheit: "F" Kelvin: "K"</h2>
Temperature:
<input type="text" id="tempinput">
<select size="3" id="initialtemp">
<option value="c" selected>C
<option value="f">F
<option value="k">K
</select>
<br>
<br>Result:
<input type="text" id="result">
<button type="button" onclick="convert()">Convert</button>
</div>




Answer

HTML

Your options need a closing tag.

<option value="c" selected>C</option>
<option value="f">F</option>
<option value="k">K</option>

JS

In order to get the value of the select element you have to use the .value property.

var valueSelected = document.getElementById("initialtemp").value;

Lastly in order to update the output element with your generated string you have to use the .value property and not the .innerHTML one.

document.getElementById("result").value = convertedF + "F" + " = " + convertedK + "K";