Disable Form Field, Preserving Submit

August 25, 2009

The “disabled” attribute on an HTML form element prevents the field from being edited. Unfortunately, it also prevents the field from being submitted in the form. If you do need to submit the field even though it’s disabled, use the following instead of the disabled attribute:

this.event.addListener( field, “click”, function(e)
{
var targ;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
targ.blur();
});

YAHOO.util.Event.addListener( field, “click”, function(e)

{

var targ;

if (e.target) targ = e.target;

else if (e.srcElement) targ = e.srcElement;

if (targ.nodeType == 3) // defeat Safari bug

targ = targ.parentNode;

targ.blur();

});

This will blur (deselect) the field as soon as you select it. Combine it with some gray styling and you’ve got a great form disabler.


Cross-Browser Null Key Code

July 17, 2008

In a login form, a JavaScript validation function was set to be called on key press or on login button click. However, the form wouldn’t submit in Firefox – only in IE.

Turns out that the function was checking the key code (e.which or e.keyCode) to see what key had been pressed – either 13 for the enter key, or 0 no key (i.e. the mouse click). But it turns out that Firefox records “no key” as a 1 instead of as a 0. I just changed the code to look for 13, 0, or 1, and we were set.

A better design would be to write two functions, one for key press and one for button click. The idea of checking the character code is foreign to the abstract logic of the button click procedure, so it’s really a hack to treat them as a single function. You can abstract any common code into a third function, of course.