Advertisement
Guest User

Untitled

a guest
Mar 11th, 2012
107
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(function() {
  17.         setValues();
  18.     });
  19.  
  20.     $(':input').keyup(function() { // anytime the keyup event fires on an input in the page
  21.         setValues();
  22.     });
  23.  
  24.     $(':radio').change(function() { // any time a radio element changes state this is fired with the element as context
  25.         if (this.id != "to_celcius") { // Did this state change occur on the to_celcius radio?
  26.             df.set(true);
  27.             dc.set(false);
  28.         } else {
  29.             df.set(false);
  30.             dc.set(true);
  31.         }
  32.     });
  33. });
  34.  
  35. $.fn.set = function(bool) {
  36.     this.attr('disabled', bool);
  37.     this.val('');
  38. };
  39.  
  40. function calc(f, x) {
  41.     x = (x == "-" || x == "") ? 0 : x; // assumes 0 if the input field is empty or a minus sign
  42.     return f ? Math.round(x * 9/5 + 32) : Math.round((x - 32) * 5/9); // depending on f, select proper equation and calculate for x
  43. }
  44.  
  45. function setValues() {
  46.     to_c = ($('#to_celcius').attr('checked') == 'checked'); // Are you converting F to C?
  47.     dc.val(to_c ? calc(false, df.val()) : dc.val());
  48.     df.val(to_c ? df.val() : calc(true, dc.val()));
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement