views:

138

answers:

2

Hey Guys,

I'm new to jQuery and have an annoying problem. I have some login fields that are filled with default text when the field is empty and then removed when clicked.

My problem is that when the user has their username/password saved (with browser), if they return to the page the login fields are filled with the users saved input as well as the default input.

$('#login input.text').each(function(i, field) {
            field = $(field);
            if (field.val().length > 0) {
                field.prev().css('display', 'none');
            }
            field.focus(function() {
                field.prev().css('display', 'none');
            }).blur(function() {
                if (field.val() == '') field.prev().css('display', 'block');
            });
        })
A: 

i would go for something like this for having default values instead of showing hiding something next to fields. Of course you can use any custom attribute instead of name but having login and password seems to be fine:

$(function(){ 
    $('#login input.text').each(function() {
        var field = $(this);
        if (!!field.val() && field.val() !=field.attr('name')) {
            field.val(field.attr('name'));
        }
    }).focus(function() {
        var field = $(this);
        if (field.val() == field.attr('name')) field.val('');
    }).blur(function() {
        var field = $(this);
        if (!!field.val()) field.val(field.attr('name'));
    });

});

vittore
+1  A: 

I would recommend using the html5 placeholder attribute.

<input type="text" placeholder="username" name="username">

Mike Taylor has written a great jQuery plugin to support browsers that don't support this attribute yet. http://github.com/miketaylr/jQuery-html5-placeholder

jebaird