• Setting a form field to null or undefined

    Apr 4 2006

    I came across another browser difference while debugging some JavaScript. Let's say you were trying to set the value of a form field the following way:

    document.getElementById('formField').value = someFunction();

    But, it just so happens that someFunction() returns null. What happens when you set a form field value to null? Well, in Firefox and Safari, the value will be set to the empty string, "". Internet Explorer and Opera will set the field to the string "null".

    Similarly, if the function forgot to return a value, the form field would get set to "undefined" (this is the same in every browser).

    The moral of the story is, be careful not to let a form field value get set to null. You could avoid both these situations by doing something like:

    document.getElementById('formField').value = someFunction() || "";

    Note: This would actually replace undefined and null as well as 0 and false with "".

  • Comments

    1. Nancy at 11:56am on November 20, 2009

    I have bunch of textboxes with a save button.
    If I enter a number in my text box and click saves, I am unable to set the field values back to 0 or to 'blank-out' the values entered in the field. If I attempt to do so the system sets the value of the field back to the previous value.
    Any idea why?
    Please help

    Commenting is now closed. Come find me on Twitter.