JavaScript - Simple Converter

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


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


<!doctype html>
<html lang="en">
  <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">

  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() {
    var km = parseFloat(txtKm.value);
    txtMiles.value = String(km * MILES_TO_KM);

  function calcKilometersFromMiles() {
    var miles = parseFloat(txtMiles.value);
    txtKm.value = String(miles * KM_TO_MILES);

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

<table border="0" cellpadding="5" cellspacing="0" style="width: 500px;">
    <td> </td>
    <td><b>Miles</b>  </td>
    <td> </td>
    <td><b>Kilometers</b>  </td>
    <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>
    <td> </td>
    <td> <button type="button" onclick="calcMilesFromKilometers();">Calculate Miles</button> </td>
    <td> </td>
    <td> <button type="button" onclick="calcKilometersFromMiles();">Calculate Kilometers</button> </td>


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 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