user1179295
user1179295

Reputation: 746

using jquery to change contents of form upon typing

I am trying to get the default value to not go away on click, but rather when the user starts typing (so they know what the field is for)....the problem is the following:

when I use onchange instead of onfocus it keeps the default value in there when they start typing. If its confusing what I am doing go to facebook and look how their search box works...thats what I am going for.

<script>

    function uFocus() {
        $('#fakeusername').hide();
        $('#username').show();
        $('#username').focus();
    }

    function uBlur() {
        if ($('#username').attr('value') == '') {
            $('#username').hide();
            $('#fakeusername').show();
        }
    }
</script>
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:gray;' type='text'  name='fakeusername' id='fakeusername' value='  Username' onfocus='uFocus()' />
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:#000000;display: none' type='text' name='username' id='username' value='' onblur='uBlur()' />

Upvotes: 1

Views: 162

Answers (3)

charlietfl
charlietfl

Reputation: 171698

Here's a method that places label over top of input and requires proper for/ID match to allow browser to do default focus of input when clicking on label. Positions label over top of input, if no value of input on blur will show label again. Using label makes it accessible

http://jsfiddle.net/UCxaZ/2

Upvotes: 0

adeneo
adeneo

Reputation: 318352

Is this what you are looking for:

$("#fakeusername").on({
    focus: function() {
        $(this).css('color', '#000');
    },
    blur: function() {
        $(this).css('color', 'grey');
    },
    keydown: function() {
        if ($(this).val()=='  Username') {
            $(this).val('');
        }
    }
});

FIDDLE

Upvotes: 0

rjz
rjz

Reputation: 16510

Two options:

In HTML5, the placeholder attribute will simulate what you want with no Javascript needed.

<input type='text'  name='fakeusername' id='fakeusername' value='Username' placeholder='Type your username' />

The second, and I believe the approach used by Facebook, is to swap a background image containing the sample text with a blank one. So you might create two background images (the first containing the words "Type your username" in the font used by the input, the second a blank) and set them to flip whenever the input is focused.

Upvotes: 2

Related Questions