unitconverter.js
contains the necessary JavaScript code to do the actual conversion. It starts with the definition of a conversion map, a dictionary holding the conversion factors for any conversion we want to define. We restrict ourselves to conversions from inches to centimeters and vice versa, but additional conversion factors can easily be added.
conversion_map = {
"inch cm":1.0/2.54,
"cm inch":2.54
};
$("button").button().click(function(){
value=$("input[name='from']").val();
f=$("select[name='tounit'] option:selected").val();
t=$("select[name='fromunit'] option:selected").val();
if(f != t){
c=conversion_map[f+' '+t];
result=parseFloat(value)*c;
}else{
result = value;
}
$("input[name='to']").val(result);
}
);
$("form *").addClass("ui-widget");
The highlighted line in the previous code is our first encounter with the jQuery and jQuery UI libraries and deserves some close attention. The $("button")
part selects...