I’m trying to write a script that will alter form elements on DOM load (by wrapping them in <div>’s etc) so i have more flexibilty in styling them. I’m attempting to do this in a way that’s unobtrusive AND object oriented (very little OO experience). I would LOVE if someone with solid OO skills (even better with prototypeJS) experience could hold my hand a little to optimize my script. I’ve utilized various prototypeJS methods, but i’m sure there’s much more I could leverage from that library that would simplify my code and make it more robust. Here’s what i’ve got so far…
[code]var CustomForms;
Event.observe(window, ‘load’, function() {
new CustomForms.initialize;
});
CustomForms = {
initialize : function() {
$$(‘.custom_form input’,’.custom_form select’,’.custom_form textarea’,’.custom_form button’).each(function(field) {
var thisField = field;
if(thisField.tagName.toLowerCase() == ‘input’) {
if(field.type == ‘submit’ || field.type == ‘button’ || field.type == ‘reset’) {
thisField.addClassName(‘custom_button’);
} else {
thisField = field.wrap(‘div’, {‘class’ : ‘custom_’+field.type});
if(field.type != ‘text’) {
if(field.checked) thisField.addClassName(‘checked’);
thisField.onclick = function() {
CustomForms.check(this);
}
}
}
} else {
if(field.tagName.toLowerCase() == ‘button’) {
thisField.addClassName(‘custom_button’);
} else {
thisField = thisField.wrap(‘div’, {‘class’ : ‘custom_’+field.tagName.toLowerCase()});
if(field.nodeName.toLowerCase() == ‘select’) {
thisField.insert({top: ‘<img src=”assets/images/pulldown_arrow.gif”/>’});
var options = field.getElementsByTagName(‘option’);
var value = options[field.selectedIndex].childNodes[0].nodeValue;
thisField.insert({top: ‘<span>’+value+'</span>’});
field.onchange=function() {
CustomForms.select(this);
}
}
}
}
thisField.onmouseover = function() {
this.addClassName(‘over’)
}
thisField.onmouseout = function() {
this.removeClassName(‘over’)
}
thisField.onmousedown = function() {
this.addClassName(‘down’)
}
thisField.onmouseup = function() {
this.removeClassName(‘down’)
}
});
}
,check : function(element) {
if(element.hasClassName(‘custom_checkbox’)) {
element.firstDescendant().checked = (element.hasClassName(‘checked’) ? false : true);
element.toggleClassName(‘checked’);
} else {
if(element.firstDescendant().checked) {
return;
} else {
element.firstDescendant().checked = true;
element.addClassName(‘checked’);
$$(‘input[name=’+element.firstDescendant().name+’]’).each(function(member) {
if(member.parentNode != element) member.parentNode.removeClassName(‘checked’);
});
}
}
}
,select : function(element) {
var options = element.getElementsByTagName(‘option’);
var value = options[element.selectedIndex].childNodes[0].nodeValue;
element.previous(1).innerHTML = value;
}
};