Sometime we need validation for onblur event, What is onblur html event? This is event when we leave text field, or textarea and move to next part, this also works with links if you have selected a link and you move to next link this means you blured previous link.
I am going to call a javaScript function from text field’s onblur event, and i will check with this function if that text field value is empty then make it default value to something suppose to Search here.. phrase.
Onblur validation to restore text field value.
First we create a text field with empty value then we will call a function restoreValue() onblur event which will restore its value to Search here.. if value of our field is empty onblur.
[code]
<input type="text" id="mySearch" value="" onblur="restoreValue();" />
[/code]
As you can see above we are calling a function restoreValue onblur event of html. We have set an ID for this field so using this ID we will get it’s value in javaScript and we will set it’s value in javaScript as well.
[code lang=”js”]
<script type="text/JavaScript">
function restoreValue() {
var currVal = document.getElementById(‘mySearch’).value;
var defaultVal = ‘Search here..’;
if(currVal == ”) {
document.getElementById(‘mySearch’).value = defaultVal;
}//if condition to check if current value is empty ends here.
}//mySearch function ends here.
</script>
[/code]
Explanation of JavaScript
In first line i am creating new variable called currVal and i am saving current value of mySearch field by getting from document get element by id and its value. Then i am creating a new variable defaultVal in which i am saving a string Search here.. after that i check in if condition if current value of currVal variable is equal to empty then put default value there. That’s it. This is how we validate onblur event and we can run any function onblur and do anything we want.