Tuesday, October 09, 2007

Neat Prototype Trick - Activate First Form Element Without a Certain Class Name

Let's say you have form with a bunch of fields that you have disabled with the "read only" attribute so the user can't change the data. Also, you have applied a css class called "readOnlyInput" so you can style the input field as read only field (different color or whatever else you like). I had such form this evening but I wanted the focus to automatically go to the first non read only element when the page is loaded. Usually, you can pass focus on a form element by doing this:
// 'myFormField' is the id of form field you want to focus on
However, if the input field already contains data, you might want to focus the field and highlight it in the same time. In that case you will do:
// 'myFormField' is the id of form field you want to focus on
That is all fine and great but what when I have a bunch of input elements and some of them might be marked "read only". To make things more complicated (as I love to do), I would hate to hard code the id of the first element I want to focus/activate. So here is the solution:
// For each input element on the form
$A($('myForm').getInputs()).each(function(formElement) {
 // If the form element does not have the class "readOnlyInput"
 if (!$(formElement).hasClassName('readOnlyInput')) {
  // Activate that element
  // Break out of the loop (prototype specific syntax here)
  throw $break;
Just so Doug's kids would understand this, here it is in psudo code:
  1. Get a list of form input elements by using Prototype's built in "getInputs" function $('myForm').getInputs()
  2. Convert the list of form inputs to a Prototype array $A($('myForm').getInputs())
  3. Now for each of the elements in the array, run a function pass in the current element $A($('myForm').getInputs()).each(function(formElement)
  4. If the current form element has a css class not matching "readOnlyInput" if (!$(formElement).hasClassName('readOnlyInput'))
  5. Activate that form element $(formElement).activate();
  6. We found the first element so break out of the loop throw $break;

1 comment:

  1. Dang man, even my kindergartner was asking, "Daddy, what does the $A function do behind the scenes?". Outstanding post, outstanding explanation, very useful and outstanding code snippet. Keep on sharing! The world is a better place because of it.


// //]]>