Friday, May 15, 2009

HTML forms - Things you should know

This is a list of things every web developer should know about forms. I didnt know these things, and thus wasted many hours banging my head against the desk. Hopefully this post will save someone else that time.

1. Disabled inputs are not submitted.

The HTML spec defines that only 'successful' controls's values will be sent in the form on submit. disabled controls arent 'successful' and are not submitted. If you want to submit a disabled control you will have to either:
  • Enable it right before submitting the form, and then disable it.
  • Copy its value into a hidden input before submit

2.
A form with only 1 text input will submit on enter in that input.

This is another little gem from the HTML spec that drove me nuts for a while. I couldnt figure out why the form was submitting on enter in an input type='text' when no key handlers were attached to the input, what was worse, my on submit validation was skipped. It turned out that if a form has a single input of type 'text' then pressing enter in this input will submit the form. To get around this you must:
  • Add another input of type text and hide it with css

3.
Internet exporer will not submit a form if it contains a file chooser with an invalid file path.

This is a fun one. IE does some rudementary form validation for you, and if it finds that you have selected a file which does not exist, it will not let you submit the form. This by itself is not a bad thing, but what is bad, is that it does not let the user, or the programmer know that the form was not submitted. As a UI programmer, I want to have an error message if the form submition fails, but I have no way of knowing it. To get around this you must:
  • Validate the path yourself using regex, and try to find invalid file paths, and raise error yourself before IE
  • Copy the value of the filechooser into a hidden input, disable the file chooser, and deal with invalid paths in serverside validation.(wont work as pointed out)

4 comments:

  1. You could just see if that post argument is set or not on the server side and deal with it as needed.

    ReplyDelete
  2. For 1, use readonly attribute instead of disabled. Problem solved.

    Of course, a hidden textbox is the alternative (better)

    ReplyDelete
  3. @nap: you are right, i dont know what i was thinking there.

    ReplyDelete
  4. "it's to prevent the upload 'sensible' file from the users computer"

    Can someone explain the reasoning here? I still don't get it.

    Also, will other browsers permit access to the full path?

    ReplyDelete