tags:

views:

77

answers:

7

I would like to use jquery to populate fields with default values. For example, say I have a field for email address and I want to add [email protected] in grey italic text in the box and the remove it once the user clicks on the field. Is there any good way to do this with a plugin or something? I would really like to avoid toggling an absolutely positioned div if possible.

+1  A: 
<input onfocus="this.select()" type="text" value="[email protected]" /> 

This highlights the text upon clicking in the text box. It means when you click it again after typing in it before, the text won't vanish again.

If you really do want the text to just vanish upon click everytime, use this.

<input onfocus="this.value=''" type="text" value="[email protected]" /> 
Liam Spencer
+4  A: 

Updated: This new version makes the same code reusable for multiple <input> elements

Try it out: http://jsfiddle.net/XTKu8/

HTML

<input id='name' class='italic' value='some name' type='text' />
<input id='email' class='italic' [email protected]' type='text' />

jQuery

$('.italic').each(function() { $(this).data('defaultValue',$(this).val()); })
    .focus(function() {
        var $th = $(this);
        if($th.val() == $th.data('defaultValue'))
            $th.toggleClass('italic').val('');
    })
    .blur(function() {
        var $th = $(this);
        if($th.val() == '')
          $th.toggleClass('italic').val($th.data('defaultValue'));
    });​

Original

Try it out: http://jsfiddle.net/ZRLK2/

HTML

<input id='email' type='text' />​

jQuery

$('#email').focus(function() {
    var $th = $(this);
    if($th.val() == [email protected]') {
        $th.val('')
            .css({'color':'#000','font-style':'normal'});
    }
})
    .blur(function() {
        var $th = $(this);
        if($th.val() == '') {
            $th.val([email protected]')
            .css({'color':'#888','font-style':'italic'});
        }
    })
    .val([email protected]')
    .css({'color':'#888','font-style':'italic'});​

EDIT: I forgot about the italic part, and should have used focus. Updated.

Also, instead of setting specific CSS styles, you may want to place those styles in a class and use .addClass() and .removeClass(), or just .toggleClass().

As karim79 noted, it is better to add classes instead of styles. You could do this instead:

.italic {
    color:#888;
    font-style:italic;
}

Then

$th.val('')
    .removeClass('italic');

$th.val([email protected]')
    .addClass('italic');
patrick dw
Loved it. Cool.
simplyharsh
+1 Nice solution. I can think of one tiny little improvement though - which would be to use `addClass('italic')` and `removeClass('italic')` instead of those chunky `.css` calls (and of course, putting the style into a class named 'italic' or such).
karim79
@karim79 - Thanks :o) and I agree. I added that note at the end of the answer, but probably a good idea to make it explicit. I'll update.
patrick dw
this is good for one input field only... and would make much effort to copy paste almost the same code for other fields... please take a look at my answer... :) http://stackoverflow.com/questions/3344465/populate-fields-with-default-values-using-jquery/3344570#3344570
Reigel
@Reigel - Just needs a little refactoring to make it reusable. http://jsfiddle.net/beU5t/
patrick dw
+1  A: 

You can do:

$( "#emailField")
   .val( "[email protected]")
   .bind( "focus", function(){
        $(this).val("");
   })
   .bind( "onblur", function {
        $(this).val("[email protected]");
   });
Artem Barger
remove `on` in `onfocus`
Reigel
That's good but you'd probably only want to set the value back to the sample value when the user hasn't typed stuff into it!
Pointy
Dont you think we need a check on blur, for not replace the text written by user. Your code will replace any text entered by user.
simplyharsh
@Pointy, @harshh you both correct. Wrote my answer out of head just a sketch for final solution, I agree need to be checked.
Artem Barger
+1  A: 

What you describe is exactly what this offers: http://code.google.com/p/jquery-watermark/

 /// Adds the watermark to the text entry areas
var watermarkText = [email protected] ';
$(function()
{
    $('.myEmailArea').watermark(watermarkText)
});

EDIT: show some CSS for this example:

.watermark
{
    color: #808080 !important;
}
Mark Schultheiss
FYI, this also puts the watermark back after you blank the field, allows special styles such as italic etc. based on CSS, good plug-in.
Mark Schultheiss
+4  A: 

demo

<input type="text" id="email" />
<input type="text" id="name" /> 

then,

$(function(){
   $('#email').focus(focus).blur(blur)[0].defaultValue="[email protected]";
   $('#name').focus(focus).blur(blur)[0].defaultValue="Type name here";
})

function focus(){
   this.value = (this.value == this.defaultValue)?'':this.value;
}
function blur(){
   this.value = (this.value == '')?this.defaultValue:this.value;
}

demo with styles

$(function(){
    $('#email, #name').addClass('default');
    $('#email').focus(focus).blur(blur)[0].defaultValue="[email protected]";
    $('#name').focus(focus).blur(blur)[0].defaultValue="Type name here";
});

function focus(){
    if (this.value == this.defaultValue) {
        this.value = '';
        $(this).removeClass('default');
    }
}
function blur(){
    if (this.value == '') {
        this.value = this.defaultValue;
        $(this).addClass('default');
    }
}​
Reigel
How would I add styles to the default values only?
Thomas
@Thomas: please see edits
Reigel
+1 - Nice solution. :o)
patrick dw
A: 

Use this CSS:

input.defaulted_input {
    color: #999999;
    font-style: italic;
}

And this Javascript:

var email_input = $("#email");
var email_value = email_input.val();
email_input.bind("focus blur", function() {
            if (this.value === email_value) {
                this.value = "";
                email_input.toggleClass("defaulted_input");
            } else if (this.value === "") {
                this.value = email_value;
                email_input.toggleClass("defaulted_input");
            }

        });​

SEE: http://api.jquery.com/toggleClass/
SEE: http://jsfiddle.net/KE43P/

Sean Vieira
A: 

You don't need jQuery for something so trivial, it's excessive.

<input type="text" value="initial value" onfocus="if (this.value=='initial value') this.value=''">
SpliFF
True, but if you already have jQuery on the page, why not use it?
Sean Vieira
because 99% of the time you're just adding extra overhead for no gain. In this case by asking the browser to search through the DOM when the object you want is already pointed to by 'this'.
SpliFF