Friday 27 May 2011

Returning Javascript array keys - numeric array

While creating rather simple JavaScript widget today, based on Date object I faced a tiny and small problem; As you all know Date objects prototype function getMonth(), returns a numeric representation of month. It means January = 0 and December of course is 11.
But lets take a simple example - You are building a drop down selection calendar, with 3 selection boxes; Year, Month and Day.
So, your month's will be not numbers but strings. Problem, how to map this with getMonth() numeric representation? Here is a small function I,ve created;

function getMonthIndex(month){
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var b = months.length
for(var i=0; i < b; i++) { if(months[i]==month) { return i; } else {return;} } }

Basically this is simple, looping through array, matching month's name's string value with appropriate value in months numeric type array and returning it's index. which in our case is what we need.
And here is a simple example how to use it in action with Jquery.

$('option').each(function(){
$(this).click(function(){
var d = new Date();
d.setMonth(getMonthIndex($(this).val())); /* Now you have used your textual option selection and swap it to numerical Date objects representation. Use your new setting for your project needs*/

});
});

In my case it was to be able to manipulate with day option selections - remove or add day's to and from selection list depending on month.
So I,ve created new Date object's property, called getMonthDays().

function getMonthDays(){
var days = [31,28,31,30,31,30,31,31,30,31,30,31];
if(this.isLeapYear()){ // google for this, there is bunch of scripts to get Leap year.
days[1] = 29;
}
return days[this.getMonth()];
}
Date.prototype.getMonthDays = getMonthDays; // quite a usable prototype, isnt't it?


Simple, you should agree? Of course I've inspired from similar scripts.
Now we are able to modify our option list manipulation function to look like this.


$('#months option').each(function(){
$(this).click(function(){
var d = new Date();
var ind =
var days = $('#days option').val(); // days and month id's are for convenience
d.setMonth(getMonthIndex($(this).val()));
var vu = 32; //(31 days + 1)
do {
$('#days option[value="+days+"]').remove();
v--
}while(d.getMonthDays() < vu) /* looping while we reach amount of day's in particular month, based on user selection */ }); });


So, easy and simple usage of numeric array key manipulation function. And power Java-scripting.

No comments:

Post a Comment