how can i rewrite these functions to be stored in a separate script and only apply to class "formInput" (which i am using for CSS styling)? there are only a few form elements, so there's not much need for loops or scripting for general cases
Something like this (if you already have a lot of class checking, get an implementation of getElementsByClassName that accepts native implementations).
Code:
onload = function () { // Presumes no other onloads
var els = document.getElementsByTagName("input"), el;
for (var i = 0; i < els.length; i++) {
el = els[i];
if (el.className == "formInput") {
el.onfocus = function () {
// Whatever
};
el.onblur = function () {
// Whatever
};
}
els = document.getElementsByTagName("textarea");
for (i = 0; i < els.length; i++) {
el = els[i];
if (el.className == "formInput") {
el.onfocus = function () {
// Whatever
};
el.onblur = function () {
// Whatever
};
}
}
Great wit and madness are near allied, and fine a line their bounds divide.
thanks for steering me in the right direction. with your help i was able to finalize this. i was able to add a simple validation function to verify that all fields are correctly filled.
Code:
var inputs = document.getElementsByTagName('input');
onload = init;
function init() {
for (i=0; i<inputs.length; i++) {
var input = inputs[i];
if (input.type == 'text') {
input.defaultText = input.value;
input.onfocus = clearText;
input.onblur = fillText;
}
}
}
function clearText() {
if (this.value == this.defaultText) {
this.value = '';
}
function fillText() {
if (this.value == '') {
this.value = this.defaultText;
}
}
function validate() { //runs on form submit
for (i=0; i<inputs.length; i++) {
var input = inputs[i];
if (input.value == input.defaultText || input.value == '') {
alert('Please fill in all fields.');
return false;
}
}
return true;
}
Originally Posted by Declan1991
Something like this (if you already have a lot of class checking, get an implementation of getElementsByClassName that accepts native implementations).
Code:
onload = function () { // Presumes no other onloads
var els = document.getElementsByTagName("input"), el;
for (var i = 0; i < els.length; i++) {
el = els[i];
if (el.className == "formInput") {
el.onfocus = function () {
// Whatever
};
el.onblur = function () {
// Whatever
};
}
els = document.getElementsByTagName("textarea");
for (i = 0; i < els.length; i++) {
el = els[i];
if (el.className == "formInput") {
el.onfocus = function () {
// Whatever
};
el.onblur = function () {
// Whatever
};
}
}
Bookmarks