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
$('myFormField').focus();
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
$('myFormField').activate();
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
$(formElement).activate();
// 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:
- Get a list of form input elements by using Prototype's built in "getInputs" function $('myForm').getInputs()
- Convert the list of form inputs to a Prototype array $A($('myForm').getInputs())
- Now for each of the elements in the array, run a function pass in the current element $A($('myForm').getInputs()).each(function(formElement)
- If the current form element has a css class not matching "readOnlyInput" if (!$(formElement).hasClassName('readOnlyInput'))
- Activate that form element $(formElement).activate();
- We found the first element so break out of the loop throw $break;
1 Comments:
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.
Post a Comment