Archive

Posts Tagged ‘JavaScript’

JQuery Timepicker Plugin

April 12th, 2009 1 comment

I had the need to create a time selecting component for a form, but I didn’t want to have lots of extra components. After a little bit of searching about I found the following JQuery UI plugin called timepicker.

This plugin will take a input box as the argument and will add three selection boxes for hours, minutes and seconds. It will then hide the original input box.

However, there were two thing that I needed that this plugin didn’t do. The first is that it was in a 12 hour format and the second is that the plugin didn’t have a second selection. So I decided to adapt that plugin in order to incorporate these things.

Here is the modified plugin.

(function($){
    jQuery.fn.timepicker = function(){
        this.each(function(){
            // get the ID and value of the current element
            var i = this.id;
            var v = $(this).val();
 
            // the options we need to generate
            var hrs = new Array('00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23');
            var mins = new Array('00','05','10','15','20','25','30','35','40','45','50','55');
            var secs = new Array('00','05','10','15','20','25','30','35','40','45','50','55');
 
            // default to the current time
            var d = new Date;
            var h = d.getHours();
            var m = d.getMinutes();
            var s = d.getSeconds();
            
            // override with current values if applicable
            // round the minutes and seconds to nearest 10
            if(v.length == 8){
                h = parseInt(v.substr(0,2));
                x = parseInt(v.substr(3,2));
                m = (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
                x = parseInt(v.substr(6,2));
                s = (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;                
            }
    
            // build the new DOM objects
            var output = '';
            
            output += '<select id="h_' + i + '" class="h timepicker">';                
            for(hr in hrs){
                output += '<option value="' + hrs[hr] + '"';
                if(parseInt(hrs[hr]) == h) output += ' selected';
                output += '>' + hrs[hr] + '</option>';
            }
            output += '</select>';
    
            output += '<select id="m_' + i + '" class="m timepicker">';                
            for(mn in mins){
                output += '<option value="' + mins[mn] + '"';
                if(parseInt(mins[mn]) == m) output += ' selected';
                output += '>' + mins[mn] + '</option>';
            }
            output += '</select>';                
    
            output += '<select id="s_' + i + '" class="p timepicker">';                
            for(ss in secs){
                output += '<option value="' + secs[ss] + '"';
                if(secs[ss] == s) output += ' selected';
                output += '>' + secs[ss] + '</option>';
            }
            output += '</select>';                
    
            // hide original input and append new replacement inputs
            $(this).css('display','none');
            $(this).after(output);
        });
        
        $('select.timepicker').change(function(){
            var i = this.id.substr(2);
            var h = $('#h_' + i).val();
            var m = $('#m_' + i).val();
            var s = $('#s_' + i).val();
            var v = h + ':' + m + ':' + s;
            $('#' + i).val(v);
        });
        
        return this;
    };
})(jQuery);

You can view and download this code here.

The plugin will also update itself with the time that is present in the text field, as long as it matches the format HH:MM:SS.

I have also setup a test page for this timeplugin.

You can run the plugin by using the following code:

$('#timepicker').timepicker();

JavaScript Round To The Nearest 5

April 11th, 2009 1 comment

I have already talked about a JavaScript function that rounds To the nearest number, but this was only useful if the number needed to be to the nearest 10 (or factor of). The following function is similar, but will round the number to the nearest 5 or 10, depending which is closer.

function round5(x)
{
    return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
}

Use the function like this:

alert(round5(12)); // returns 10
alert(round5(14)); // returns 15

Categories: JavaScript Tags: , , , ,

JavaScript Round To Nearest Number

April 11th, 2009 No comments

The JavaScript Math.round() function will round a decimal to the nearest whole number, but I found that I needed was to round a number to the nearest 10. So after a bit of thinking I realised that I could divide the value by 10, round it using the round() function and then multiply the result by 10.

So taking it a step further I decided to create a function that would round a number to the nearest 10, 100, 1000 or whatever value is entered. If this value is less than 0 then do the reverse by multiplying and dividing the number by the given value of accuracy. Here is the function.

function roundNearest(num, acc){
    if ( acc < 0 ) {
        num *= acc;
        num = Math.round(num);
        num /= acc;
        return num;
    } else {
        num /= acc;
        num = Math.round(num);
        num *= acc;
        return num;
    }
}

Here are some tests of the function.

alert( roundNearest(12345, 1000) ); // 1200
alert( roundNearest(12345.1234, -100) ); //12345.12

This function can be simplified a little by putting all of the calculations onto one line.

function roundNearest(num, acc){
    if ( acc < 0 ) {
        return Math.round(num*acc)/acc;
    } else {
        return Math.round(num/acc)*acc;
    }
 }

PHP foreach Equivalent In JavaScript

March 31st, 2009 No comments

If you are familiar with PHP you will have come across the forloop at some point. When learning JavaScript it is important to remember that it also has the ability to do the equivalent of the PHP forloop.

The following snippet shows the creation of an array of things that can’t be referenced by a normal for loop due to the odd numbering of the keys.

var arrThings= new Array();
 
arrThings[3] = 'thing 1';
arrThings[42] = 'thing 2';
arrThings[47] = 'thing 3';
arrThings[32] = 'thing 4';
 
var output = '';
 
for ( var thing in arrThings ) {
 output += arrThings[thing];
}
alert(output);

The variable thing is now the iterator and will iterate through each element of the array. By using this code you no longer have to include code that thinks about the length of the array.

Categories: JavaScript Tags: , , , , ,

Display JavaScript Source Programatically

March 23rd, 2009 2 comments

If you are running a JavaScript example page you can use the following function that will take the last script element on the page and print it out in a code tag. It uses JQuery to do the work, so you will need to include that library before using this function.

<script type="text/javascript">//<![CDATA[
 function displaySource(name) {
  $('<code>'
   + $('#display-' + name).prevAll('script').eq(0).html()
   .replace(/^\s*|\s*$/g, '')
   .split('\n').slice(1, -1).join('\n')
   .replace(/(^|\n) /g, '$1')
   .replace(/('[^']*')/g, '<em>$1</em>')
  + '</code>')
  .insertAfter('#display-' + name);
 }
//]]></script>

The function works by selecting the current script tag and finding all script elements before it. It then selects the first one it finds and outputs the contents to a code tag. It uses a few regular expressions to convert some of the characters to a more human readable format. The function is called like this.

<script type="text/javascript" id="display-test">displaySource("test");</script>