Thursday, July 17, 2008

Missing form ACTIONs

Say you want to disable a submit button when it's clicked, to prevent the user from submitting twice:

<form name="myform">
  <input type="submit" value="Submit" onclick="this.disabled = 'true';">        
</form>

On Windows, this works fine in IE but not in Firefox. Or so it appears. What's going on?

Oops, you forgot an ACTION attribute in your form. (It's okay, this is common if you're planning an Ajax-style app.) Without it, IE just ignores the submit click, but Firefox uses the current page as the default action. So it effectively reloads the page, resetting the button state.

The thing is, the submit button is being disabled in FF, just like in IE, but depending on how fast the page reloads, you might not even notice.

Wednesday, July 16, 2008

Function reference vs. function call

Here's a JavaScript function definition:
function foo() {
  alert('foo!');
}
You can refer to that function like this:
foo
And here is how to call (execute) the function:
foo()
Even experienced developers new to JS tend to get these confused. For example, jQuery's getJSON method allows you to specify a function to be executed once the operation is complete. Be careful not to plug in the function call when what you really need is a function reference:
$.getJSON( "action.php", {data:'some data here'}, foo() );
This will execute the foo function instantly. Not what you want. So leave off the parens:
$.getJSON( "action.php", {data:'some data here'}, foo );
This merely passes a reference to the function. It won't execute until it's called by jQuery.