View Full Version : Shortening a huge list using an array value

05-09-2013, 06:57 PM
Hello Guru's

I need your help,

As you can see below, I will end up having a huge list of code to accomplish an onblur and on focus scenario for a div and an input field. Is there a way to create a "list" and loop through it to accomplish what this code does line by line? Since I will have over 20 fields the page of code will be quite long.

document.getElementById('f1').onfocus = function() {
document.getElementById('f1').style.border = '1px solid #0033CC'
document.getElementById('div_rssims_prefix').style.color = '#0033CC'
document.getElementById('f1').onblur = function() {
document.getElementById('f1').style.border = '1px solid #ABADB3'
document.getElementById('div_rssims_prefix').style.color = ''
document.getElementById('f2').onfocus = function() {
document.getElementById('f2').style.border = '1px solid #0033CC'
document.getElementById('div_rssims_firstname').style.color = '#0033CC'
document.getElementById('f2').onblur = function() {
document.getElementById('f2').style.border = '1px solid #ABADB3'
document.getElementById('div_rssims_firstname').style.color = ''
document.getElementById('f3').onfocus = function() {
document.getElementById('f3').style.border = '1px solid #0033CC'
document.getElementById('div_rssims_middlename').style.color = '#0033CC'
document.getElementById('f3').onblur = function() {
document.getElementById('f3').style.border = '1px solid #ABADB3'
document.getElementById('div_rssims_middlename').style.color = ''

An ideal list would be:



05-09-2013, 10:07 PM
You can probably do even better than that, I would have to see the markup, but something like:

var inputs = document.getElementsByTagName('input'), i = inputs.length, re = /^f\d+$/;
function focusfunc(){
this.style.borderColor = this.previousSibling.style.color = '#0033CC';
function blurfunc(){
this.style.borderColor = '#ABADB3';
this.previousSibling.style.color = '';
while(--i > -1){
inputs[i].onfocus = focusfunc;
inputs[i].onblur = blurfunc;

The only thing I'm not sure of is the previousSibling bit. That is an attempt to get is a reference to the div_rssims_? for that input.

I'm thinking that perhaps that might not be the previousSibling, and I'm thinking that the ? might be the name of the input, but I can't know for sure without seeing the markup. If it is or is something like that, we can use it to get the reference.

If you want more help, please show me the HTML markup that goes with this.