Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  190] [ 5]  / answers: 1 / hits: 24758  / 11 Years ago, wed, february 27, 2013, 12:00:00

I'm trying to do a Celsius/Fahrenheit conversion calculator, with a button for each conversion and the result being displayed in the appropriate textbox. I must be missing something obvious here... I'm brand new to javascript and am just not getting it. Here's what I have done so far:



<!DOCTYPE html>
<html>
<head>
<meta charset = utf-8/>
<title>Convert Fahrenheit and Celsius</title>
<script type=text/javascript>
<!--
function convertToC() {
var fTempVal = parseFloat(document.getElementById('fTemp').value);
var cTempVal = (fTempVal - 32) * (5/9);
document.getElementById('cTemp').value = cTempVal;
}

function convertToF() {
var cTempVal = parseFloat(document.getElementById('cTemp').value);
var fTempVal = (cTempVal * (9/5)) + 32;
document.getElementById('fTemp').value = fTempVal;
}
// -->
</script>
</head>
<body>
<form name=conversionForm>
<table border=1>
<tbody>
<tr>
<td>Fahrenheit</td>
<td><input name=fTemp type=text/></td>
<td><button onclick=convertToC>Convert to Celsius</button></td>
</tr>
<tr>
<td>Celsius</td>
<td><input name=cTemp type=text/></td>
<td><button onclick=convertToF>Convert to Fahrenheit</button></td>
</tr>
</form>
</tbody>
</table>
</body>
</html>

More From » html

 Answers
4

You have a few errors. See this corrected jsFiddle example.




  1. Your input boxes were missing IDs that you were trying to reference with document.getElementById

  2. Your HTML was improperly closed.

  3. Your buttons were missing types which makes them default to submit when you really wanted just button

  4. To prevent the form from actually being submitted you should return false.



JavaScript



    function convertToC() {
var fTempVal = parseFloat(document.getElementById('fTemp').value);
var cTempVal = (fTempVal - 32) * (5 / 9);
document.getElementById('cTemp').value = cTempVal;
return false;
}

function convertToF() {
var cTempVal = parseFloat(document.getElementById('cTemp').value);
var fTempVal = (cTempVal * (9 / 5)) + 32;
console.log(fTempVal);
document.getElementById('fTemp').value = fTempVal;
return false;
}


HTML



<form name=conversionForm>
<table border=1>
<tbody>
<tr>
<td>Fahrenheit</td>
<td>
<input name=fTemp id=fTemp type=text />
</td>
<td>
<button type=button onclick=convertToC();return false>Convert to Celsius</button>
</td>
</tr>
<tr>
<td>Celsius</td>
<td>
<input name=cTemp id=cTemp type=text />
</td>
<td>
<button type=button onclick=convertToF();return false>Convert to Fahrenheit</button>
</td>
</tr>
</tbody>
</table>
</form>

[#79953] Tuesday, February 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyriquehenryq

Total Points: 248
Total Questions: 81
Total Answers: 105

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
;