views:

293

answers:

4

hey, ive been trying to have a default value in a text input, then with jQuery, when you "onfocus" the textbox, it makes the text black (default a light gray), and deletes the default value. I think you know what im talking about, so do you guys know how to accomplish this?

+1  A: 

The jquery watermark plugin allows you to achieve the desired effect.

Darin Dimitrov
A: 
$('input:text').bind({
    focus: function () {
        var self = $(this);

        if (self.val() == self.attr('defaultValue')) {
            self.val('').removeClass('default');
        };
    },
    blur: function () {
        var self = $(this),
            val = jQuery.trim(self.val());

        if (val == "" || val == self.attr('defaultValue')) {
          self.val(self.attr('defaultValue')).addClass('default');  
        };
    }
}).trigger('blur');

Have a CSS class of default which sets the text color to whatever you desire.

Example Usage: http://www.jsfiddle.net/2S9hW/

Matt
+2  A: 
<input class="txtClass" type="text" defaultVal="Enter your Name" />
<input class="txtClass" type="text" defaultVal="Enter your Designation" />

javascript

$('body').ready(function(){
  $('.txtClass').each( function () {
    $(this).val($(this).attr('defaultVal'));
    $(this).css({color:'grey'});
      });

  $('.txtClass').focus(function(){
    if ( $(this).val() == $(this).attr('defaultVal') ){
      $(this).val('');
      $(this).css({color:'black'});
    }
    });
  $('.txtClass').blur(function(){
    if ( $(this).val() == '' ){
      $(this).val($(this).attr('defaultVal'));
      $(this).css({color:'grey'});
    }
    });
});

See working example: http://jsbin.com/ovida3
http://jsbin.com/ovida3/2

Rakesh Juyal
A: 

Your basiclly creating what the placeholder attribute of the HTML5 text element supports. So you should just use the placeholder attribute and then check if the browser supports the placeholder functionality:

function supports_input_placeholder() {
    var i = document.createElement('input');
    return 'placeholder' in i;
}
if (!support_input_placeholder()) {
    $(':text').focus(function(){
        var self = $(this);
        if (self.val() == self.attr('placeholder')) {
            self.val('');
        }
    }).blur(function(){
        var self = $(this),
            value = $.trim(self.val());
        if(val == '') {
            self.val(self.attr('placeholder');
        }
    });
}

<input type="text" name="desc" placeholder="My Email Account">
PetersenDidIt