JavaScript - Simple Converter

From NoskeWiki
Jump to navigation Jump to search
Basic interface of online conversion tool

About

NOTE: This page is a daughter page of: JavaScript


A very simple JavaScript/HTML example with a single table, two text inputs and two buttons which allow you to convert miles to kilometers and back again.


Simple Miles to Kilometers Converter

convert_km_to_miles.html:

<!doctype html>
 
<html lang="en">
<head>
  <meta charset="utf-8">
 
  <title>Miles to Kilometers Converter</title>
  <meta name="description" content="Simple site for converting miles to kilometers">
  <meta name="author" content="Andrew Noske">

  <script>
  var txtMiles;
  var txtKm;

  var KM_TO_MILES = 0.621371;
  var MILES_TO_KM = 1.60934;

  function initElements() {
    if (!txtMiles) {  // Lazy initialization.
      txtMiles = document.getElementById("txt-miles");
      txtKm = document.getElementById("txt-km");
    }
  }

  function calcMilesFromKilometers() {
    initElements();
    var km = parseFloat(txtKm.value);
    txtMiles.value = String(km * MILES_TO_KM);
  }

  function calcKilometersFromMiles() {
    initElements();
    var miles = parseFloat(txtMiles.value);
    txtKm.value = String(miles * KM_TO_MILES);
  }
  </script>
</head>
 
<body>

<b>Miles To Kilometers Converter</b> <br>
<br>

<table border="0" cellpadding="5" cellspacing="0" style="width: 500px;">
<tbody>
  <tr>
    <td> </td>
    <td><b>Miles</b>  </td>
    <td> </td>
    <td><b>Kilometers</b>  </td>
  </tr>
  <tr>
    <td>miles: </td>
    <td><input id="txt-miles" size="20" type="text" value="50"/> </td>
    <td>km: </td>
    <td><input id="txt-km" size="20" type="text" value=""/> </td>
  </tr>
  <tr>
    <td> </td>
    <td> <button type="button" onclick="calcMilesFromKilometers();">Calculate Miles</button> </td>
    <td> </td>
    <td> <button type="button" onclick="calcKilometersFromMiles();">Calculate Kilometers</button> </td>
  </tr>
</table>

</body>
</html>


Code license
For all of the code on my site... if there are specific instruction or licence comments please leave them in. If you copy my code with minimum modifications to another webpage, or into any code other people will see I would love an acknowledgment to my site.... otherwise, the license for this code is more-or-less WTFPL (do what you want)! If only copying <20 lines, then don't bother. That said - if you'd like to add a web-link to my site www.andrewnoske.com or (better yet) the specific page with code, that's a really sweet gestures! Links to the page may be useful to yourself or your users and helps increase traffic to my site. Hope my code is useful! :)



See Also