Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var df, dc, cb; // declare variables
- $(document).ready(function() { // once the document and all of it's elements are loaded and ready to go
- // obtain elements as jQuery objects
- df = $('#degrees_fahrenheit');
- dc = $('#degrees_celcius');
- cb = $('#convert');
- $(':input').keydown(function(e) { // anytime the keydown event fires on an input on the page
- unicode = e.keyCode ? e.keyCode : e.charCode; // get the unicode of the key pressed
- return (String.fromCharCode(unicode).match(/^[0-9]+$/) != null) || // is it a number pressed OR
- (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
- (unicode == 8 || unicode == 37 || unicode == 39 || unicode == 46); // is backspace left right or delete key?
- });
- cb.click(setValues);
- $(':input').keyup(setValues);
- $(':radio').change(function() { // any time a radio element changes state this is fired with the element as context
- df.set(this.id != "to_celcius");
- dc.set(this.id == "to_celcius");
- });
- });
- $.fn.set = function(bool) {
- this.attr('disabled', bool);
- this.val('');
- };
- function calc() {
- x = $('#to_celcius').attr('checked') == 'checked' ? df.val() : dc.val();
- x = x == "-" || x == "" ? 0 : x; // assumes 0 if the input field is empty or a minus sign
- 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
- }
- function setValues() {
- if ($('#to_celcius').attr('checked') == 'checked') { // Are you converting F to C?
- dc.val(calc());
- } else {
- df.val(calc());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement