Using jQuery's .live/.bind to affect input created by a for loop
I have two arrays, one with input names, and one with the value to give each input. There are 7 inputs, so I made a loop to fill out each input with it's value, then make it so that the text will disappear when that input is focused, and restore the original value text if nothing was typed. Is this possible to do through a loop with jQuery? It seems to me .live and .bind won't work for this purpose. Will I have to hardcore in开发者_如何学运维 each input event focus&blur event?
for (var i=0;i<7;i++) {
$('#user_' + input_names[i]).attr('value', default_values[i]);
$('#user_' + input_names[i]).live("blur", function(){
if(this.value == '')this.value=default_values[i];
});
$('#user_' + input_names[i]).live("focus", function(){
if(this.value == default_values[i])this.value='';
});
}
Update here, releasing the arrays as Eric requested:
var input_names = ['username', 'password'];
var default_values = ['Username', 'Password'];
for (var i=0;i<2;i++) {
$('#user_' + input_names[i]).attr('value', default_values[i]);
$('#user_' + input_names[i]).blur(function(){
if(this.value == '')this.value=default_values[i];
});
$('#user_' + input_names[i]).focus(function(){
if(this.value == default_values[i])this.value='';
});
}
Looks like you're looking for the HTML5 placeholder
attribute. Just change your HTML to this:
<input id="user_username" placeholder="Username" />
<input id="user_password" placeholder="Password" />
If you want backwards compatibility, there's a jQuery plugin for that. With the plugin referenced, just do this:
$('input[placeholder]').placeholder();
As for what's wrong with your initial code, I suspect there's a closure problem, and i
is retaining the value of 7. You'd do better to rewrite it like this:
var inputDefaults = {username: 'Username', password: 'Password'};
$.each(inputDefaults, function(field, defaultValue) {
$('#user_' + field)
.attr('value', defaultValue);
.blur(function() {
if($(this).val() == '')
$(this).val(defaultValue);
})
.focus(function(){
if($(this).val() == defaultValue)
$(this).val('');
});
});
精彩评论