开发者

how to write a onfocus event in jquery

I have a fied usernam having value = 'Your Name' After Validation of this fails it becomes : 'Enter Your Name'

But I want that when I click this field or onfocus this 'Enter Your Name' vanishes with empty string.

How to write on focus event in jqu开发者_运维百科ery?


What you’re looking for has been standardized in HTML5 as the placeholder attribute. You should use this, and then use JavaScript to recreate this functionality for browsers who don’t support it natively yet.

Just write your HTML like this:

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

It will automatically work in modern browsers, no JavaScript required!

If you want to support older browsers, feel free to use my Placeholder jQuery plugin, which will automatically make HTML like that work in every relevant browser. Just include the plugin and then go like:

$('input, textarea').placeholder();

…and the plugin will take care of the rest for you. You can view a demo here: http://mathiasbynens.be/demo/placeholder


$field.bind('focus.emptyfield', function() {
  if ($(this).val() == 'Enter your name') {
    $(this).val('');
  }
}

assuming $field is your jQuery reference to your input field

note: between onclick and onfocus, the latter is the best event to handle because it is device-independent

note2: always use namespaced events (so you could safety unbind them later)


Either

http://api.jquery.com/focus/

$(selector).focus(function);

Or, in case you dynamically load the content (ajax, etc)

http://api.jquery.com/live/

$(selector).live("focus",function);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜