Advertisement
Guest User

Untitled

a guest
Mar 11th, 2012
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var df, dc, cb; // declare variables
  2.  
  3. $(document).ready(function() { // once the document and all of it's elements are loaded and ready to go
  4.     // obtain elements as jQuery objects
  5.     df = $('#degrees_fahrenheit');
  6.     dc = $('#degrees_celcius');
  7.     cb = $('#convert');
  8.  
  9.     $(':input').keydown(function(e) { // anytime the keydown event fires on an input on the page
  10.         unicode = e.keyCode ? e.keyCode : e.charCode; // get the unicode of the key pressed
  11.         return (String.fromCharCode(unicode).match(/^[0-9]+$/) != null) || // is it a number pressed OR
  12.         (unicode == 109 && this.selectionStart == 0 && this.value.indexOf('-') == -1) || // is minus key and is caret in first position, and there are no minus signs in the field already? OR
  13.         (unicode == 8 || unicode == 37 || unicode == 39 || unicode == 46); // is backspace left right or delete key?
  14.     });
  15.  
  16.     cb.click(setValues);
  17.     $(':input').keyup(setValues);
  18.  
  19.     $(':radio').change(function() { // any time a radio element changes state this is fired with the element as context
  20.         df.set(this.id != "to_celcius");
  21.         dc.set(this.id == "to_celcius");
  22.     });
  23. });
  24.  
  25. $.fn.set = function(bool) {
  26.     this.attr('disabled', bool);
  27.     this.val('');
  28. };
  29.  
  30. function calc() {
  31.     x = $('#to_celcius').attr('checked') == 'checked' ? df.val() : dc.val();
  32.     x = x == "-" || x == "" ? 0 : x; // assumes 0 if the input field is empty or a minus sign
  33.     return $('#to_celcius').attr('checked') == 'checked' ? Math.round((x - 32) * 5/9) : Math.round(x * 9/5 + 32); // depending on f, select proper equation and calculate for x
  34. }
  35.  
  36. function setValues() {
  37.     if ($('#to_celcius').attr('checked') == 'checked') { // Are you converting F to C?
  38.         dc.val(calc());
  39.     } else {
  40.         df.val(calc());
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement