Thursday, January 28, 2010

Reloading Captcha Images in JavaScript

The problem: when the form input is rejected, we want to load a new captcha. However, the browser might not understand that we want to load a new image in place of the one in the cache. Why? Because the image looks like this:
<img src="captcha.php" id="img_captcha">
and the JavaScript to reload the image looks like this:
document.getElementById('img_captcha').src = 'captcha.php';
Thus, from the browser's perspective, the image source should stay the same.

The solution: add a '#' to the end of the url:
document.getElementById('img_captcha').src = 'captcha.php';

Wednesday, January 27, 2010

Handing Checkboxes with jQuery

To determine whether a specific checkbox has been checked:

if ($('#edit-checkbox-id:checked').val() !== null) { // Insert code here. }

Another variation:

var checked =
$('#edit-checkbox-id:checked').val() == 'on';

Courtesy of: http://drupal.org/node/116548

Sunday, January 17, 2010

Decimal Truncation in JavaScript

Newer browsers provide a new toFixed() function that does the trick:

var myVar = new Number(4.12345678);
var x = myVar.toFixed(3); // x = 4.123

For older browsers, a slightly more cumbersome method in needed:

var myVar = 4.12345678;
var x = parseInt(myVar * 1000) / 1000; // x = 4.123

Saturday, January 16, 2010

Check if JavaScript Variable is Defined

function isdefined(variable)
{
return (typeof(variable) != ‘undefined’);
}


Courtesy of: http://jehiah.cz/archive/javascript-isdefined-function (and after testing what worked for me)

Note: there's interesting quirk in IE wherein if there's a div/span with the same id (for example, you want to check if the variable "test1" exists, and you have a span with the id of "test1"), then typeof(test1) will return "object", which can obviously lead to unwanted results.

Wednesday, January 13, 2010

ExtJS JsonStore - Passing POST Parameters

var myStore = new Ext.data.JsonStore({
url: 'http://www.mysite.com/ajaxrequest.php',
baseParams: {'member_id':mem_id},
sortInfo: {field:'...', direction:'ASC'},
fields: [ ... ]
});

JSON Associative Arrays

Given a JSON associative array of the following format:
var myList = {'123' : 'big', '456':'small'}

I wanted to be able to parse through this array whilst examining both the value of the key and..ummm...the value of the value. After a bit of searching, I came up with the solution:


for (var item in myList)
{
alert(item); // will display '123' and then '456'
alert(myList[item]); // will display 'big' and then 'small'
}

Date Conversion

The basic algorithm for converting seconds to days/hours/minutes/seconds:

(time = x seconds)
days = time / 86400
hours = (time / 3600) - (days * 24)
minutes = (time / 60) - (days * 1440) - (hours * 60)
seconds = time mod 60