Text Hints with JQuery and JavaScript for loop
- by lpdahito
Hey guys!
I'm developing a small app where i ask users to put some info.
I want to show text hints in the input fields.
I do this in a for loop...
When the page is loaded, the hints are displayed correctly but nothing happens on 'focus' and 'blur' events...
I'm wondering why since when I don't use a 'for loop' in my js code, everything works find...
By the way the reason I use a for loop is because I don't want to repeat myself following 'DRY' principles...
Thx for your help!
LP
Here's the code:
<script src="/javascripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var form_elements = ['#submission_url', '#submission_email', '#submission_twitter']
var text_hints = ['Website Address', 'Email Address', 'Twitter Username (optional)']
$(document).ready(function(){
for(i=0; i<3; i++) {
$(form_elements[i]).val(text_hints[i]);
$(form_elements[i]).focus(function(i){
if ($(this).val() == text_hints[i]) {
$(this).val('');
}
});
$(form_elements[i]).blur(function(i){
if ($(this).val() != text_hints[i]) {
$(this).val(text_hints[i]);
}
});
}
});
</script>