Useful Javascript: Prototype for your forms

Proposed subtitle: “Ease into Prototype.”

You started using the [Prototype JS lib](http://prototype.conio.net/) everyone was talking about. Everyone was doing AJAX stuff, animating little boxes, and you did not have the time for that. You had a day job.

But then one day: a use case appeared. You inserted some stuff in the HTML, in a form validation. This was the form:

`
` `` `` `` `
`

You had decided! This form was to be checked and validated using some neat JS stuff in Prototype. You included it:

``

And in the Javascript function `check_this_baby()`, you had this:

  `  var labeltext = "Fill that out, too!";`
  `  if (!Field.present("idcity"))`
  `{`
    `new Insertion.After('idcity', labeltext);	`
  `}`
  `if (!Field.present("idstreet"))`
  `{`
    `new Insertion.After('idstreet', labeltext);	`
  `}`

See! It does an INSERTION of labeltext, after the element with given ID. But only if there is anything present in the fields with given ID. (The Field.present() can even return true/false when given a list of elements! I love that little guy.)

But the next time you activated the above, the page wrote the labeltext again. `Fill that out again!Fill that out again!` Looked bad.

So you add a class to the STRONG element:

  `  var labeltext = "Fill `
  `that out, too!";`

This enabled you to use the new `getElementsByClassName` thing of Prototype. It returns a list of elements that have given class name on them. We did this to remove the labeltext text before looking at the form again:

  `var lbls = document.getElementsByClassName("removable");`
  `  for (i=0; i

As you can see the Prototype library does a few things Just Right. Read the finer details at the [Unofficial docs for Prototype](http://www.sergiopereira.com/articles/prototype.js.html).

Published by Olle Jonsson

Human. Wears glasses and often a smile.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.