March 24, 2012

onBlur Event on multiple textfields

Question by deepanka

I am creating a web form and inorder to validate the text fields am using onblur event. But what happens is if I leave a textfield empty and go to other a message box appears and when i try to go back to previous one onblur event of the second one is triggered and it goes like an infinite loop. And i cannot use document.form.write.
Is there any other way,using javascript,to print error message?

Answer by Starx

It will be easy if you use jQuery for this.

$('input[type="text"]').blur(function() 
     ...
});

Pure javascript way would be something like

var inputs = document.getElementsByTagName('input');

for (var i = 0; i < inputs.length; i++)
    inputs[i].onblur = functionHandler;

// Common function
function functionHandler() {
    if(this.value == "") { //get the value of tb triggering the event
        alert('empty'); //show the message
    }        
}

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!