Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove/add value onfocus/onblur if empty in jquery, input field

Tags:

jquery

I know there exists many questions about this, but I dont know what to search.

I have a email field, and I want it to have "Write your email here" and when you click/do onfocus it should disappear. Although if you did not write something and go onblur it should appear again.

like image 889
Karem Avatar asked Sep 11 '11 10:09

Karem


People also ask

How check input field is empty or not in jQuery?

Answer: Use the jQuery val() Method You can use the val() method to test or check if inputs are empty in jQuery.

How do you remove input field focus?

The blur() method removes focus from an element.

How Stop focus in jQuery?

In jQuery by using blur() property we can remove focus from input textbox field.


3 Answers

1. Markup

<input id="email" name="email" type="text" value="Write your email here" />

2. jQuery

$('#email')
  .on('focus', function(){
      var $this = $(this);
      if($this.val() == 'Write your email here'){
          $this.val('');
      }
  })
  .on('blur', function(){
      var $this = $(this);
      if($this.val() == ''){
          $this.val('Write your email here');
      }
  });​

3. Demo

jQuery input placeholder

like image 141
Shef Avatar answered Nov 15 '22 22:11

Shef


You should use HTML5 placeholder instead and use a jquery plugin for older browsers
http://diveintohtml5.ep.io/forms.html

Running example here:
http://jsfiddle.net/AamkB/

There are a lot of jquery plugins for placeholder, i used this one:
http://webcloud.se/code/jQuery-Placeholder/

like image 36
herkulano Avatar answered Nov 15 '22 20:11

herkulano


You can use the inline JavaScript tags onblur / onfocus . Maybe not the most 'clean' HTML code but it certainly works in all browsers! (Didn't try IE5.5 / 6.0, but hey, who is using these oldies nowadays?! ^_^)

<input type="text" name="aSweetInputField" value="Your textfield value" 
class="anyClass"  onclick="if (this.defaultValue==this.value) this.value=''" 
onblur="if (this.value=='') this.value=this.defaultValue">

That's it!

like image 26
Jim van Aalst Avatar answered Nov 15 '22 22:11

Jim van Aalst