Jquery - form labels
I have a simple login form with 2 fields, user and pass. I am trying to get the labels inside the inputs to hide on focus, then come back on blur if nothing was entered, but the password label keeps reappearing in the username input and I can't figure out why.
form:
<form method="post" id="nav-login-fo开发者_高级运维rm" class="float-right" action="">
<fieldset>
<div>
<label id="login-user-label" for="user">user</label>
<input id="login-user" class="float-left" type="text" name="user" />
</div>
<div >
<label id="login-pass-label" for="pass">pass</label>
<input id="login-pass" class="float-left" type="password" name="pass" />
</div>
<div>
<input class="button float-left" type="submit" name="submit" value="login" />
</div>
</fieldset>
</form>
javascript:
$("#login-user")
.bind("focus.labelFx", function(){
$("#login-user-label").hide();
})
.bind("blur.labelFx", function(){
$("#login-user-label")[!("#login-user").value ? "show" : "hide"]();
})
.trigger("blur.labelFx");
$("#login-pass")
.bind("focus.labelFx", function(){
$("#login-pass-label").hide();
})
.bind("blur.labelFx", function(){
$("#login-pass-label")[!("#login-pass").value ? "show" : "hide"]();
})
.trigger("blur.labelFx");
You could try that
$("#nav-login-form input")
.bind("focus.labelFx", function(){
$(this).prev().hide();
})
.bind("blur.labelFx", function(){
$(this).prev()!this.value ? "show" : "hide";
})
.trigger("blur.labelFx");
taken from here http://blog.stannard.net.au/2011/01/07/creating-a-form-with-labels-inside-text-fields-using-jquery/
or try this code that I hav echanged for you
$("form.login input").focus( function()
{ $(this).prev().hide();
})
.blur( function()
{
if ($(this).val() == '') {
$(this).prev().show();
} else {
$(this).prev().hide();
}
});
I think you are missing a couple of "$" and use of "val()"
Try this optimized code...
$(".float-left")
.bind("focus.labelFx", function(){
$(this).prev().hide();
})
.bind("blur.labelFx", function(){
$(this).prev()[!$(this).val() ? "show" : "hide"]();
})
.trigger("blur.labelFx");
Example: http://jsfiddle.net/ZZqFt/
Or you're code with IDs but fixed...
$("#login-user")
.bind("focus.labelFx", function(){
$("#login-user-label").hide();
})
.bind("blur.labelFx", function(){
$("#login-user-label")[!$("#login-user").val() ? "show" : "hide"]();
})
.trigger("blur.labelFx");
$("#login-pass")
.bind("focus.labelFx", function(){
$("#login-pass-label").hide();
})
.bind("blur.labelFx", function(){
$("#login-pass-label")[!$("#login-pass").val() ? "show" : "hide"]();
})
.trigger("blur.labelFx");
Which can be found here... http://jsfiddle.net/ZZqFt/1/
精彩评论