Friday, June 21, 2013

JavaScript: convert between units



Below is the JavaScript to convert between pound and Kg in mass:
<html>
<head>
<title>JavaScript to convert unit</title>
<h1>Convert between kg and pound in mass</h1>
<script language='JavaScript' type='text/JavaScript'>
function validate(type) {
    if(document.form1.textinput.value=='')
      {
          alert('Fill the Input box before submitting');
          return false;
    } else {
          var res0=document.form1.textinput.value;
          var unit1=" lb";
          var unit2=" kg";
          if(type=="to_lb"){
          var res=2.20462*res0;
          document.getElementById("result").innerHTML=res0+unit2+" = "+res.toFixed(2) + unit1;
    }else{
          var res=0.453592*res0;
          document.getElementById("result").innerHTML=res0+unit1+" = "+res.toFixed(2) + unit2;
    }

    return false;
    }
}
</script>
</head>
<body>
<form name='form1' action='' method='post'
onSubmit='return validate();'>
Input :<input type=text name=textinput size=10>
<input type=button value='Convert to Kg' onClick=validate('to_kg');>
<input type=button value='Convert to Pound' onClick=validate('to_lb');>

</form>
<div id=result></div>
</body>
</html> 

Demo:


Input :

No comments:

Post a Comment