Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript clear field value input

I am making a simple form and i have this code to clear the initial value:

Javascript:

function clearField(input) {
    input.value = "";
};

html:

<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);"/>

But what i don't want is that if the user fills the input but clicks it again, it gets erased. I want the field to have the starter value "Name" only if the input is empty. Thank you in advance!


2 Answers

do like

<input name="name" id="name" type="text" value="Name" 
   onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>

and js

function fillField(input,val) {
      if(input.value == "")
         input.value=val;
};

function clearField(input,val) {
      if(input.value == val)
         input.value="";
};

update

here is a demo fiddle of the same

like image 191
Mithun Satheesh Avatar answered Sep 15 '25 04:09

Mithun Satheesh


Here is one solution with jQuery for browsers that don't support the placeholder attribute.

$('[placeholder]').focus(function() {
  var input = $(this);

  if (input.val() == input.attr('placeholder')) {
    input.val('');
    input.removeClass('placeholder');
  }
}).blur(function() {
  var input = $(this);

  if (input.val() == '' || input.val() == input.attr('placeholder')) {
    input.addClass('placeholder');
    input.val(input.attr('placeholder'));
  }
}).blur();

Found here: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

like image 23
lekksi Avatar answered Sep 15 '25 04:09

lekksi