0

I have a form which contains some inputs with an initial value. I want when someone click on some input and click off the default value will go back. and If he click on it and type something in, it won't try to erase what he put if he go back to click on it again.

this is the code I tried :

<input type="text" name="prenom" value="Prénom" onfocus="this.value = this.value=='Prénom'?'':this.value;" onblur="this.value = this.value==''?'Prénom':this.value;"/>

Isn't there any other method to do that, because this code is long.

Croviajo
  • 253
  • 1
  • 8
  • 17

4 Answers4

3

If you aren't worried about older browsers, you can use this:

<input type="text" name="prenom" placeholder="Prénom"/>
alex
  • 701
  • 5
  • 5
2

Use Placeholder

<input type="text" name="prenom" placeholder="Prénom"/>

See for Support

You can apply styles to placeholder text too:-

::-webkit-input-placeholder {
   color: #000000;
}

:-moz-placeholder { /* Firefox 18- */
   color:  #000000;  
}

::-moz-placeholder {  /* Firefox 19+ */
   color:  #000000;  
}

:-ms-input-placeholder {  
   color:  #000000; 
}

Demo

There are numerous plyfills available for placeholder support in older browsers you can take a look at them.. Here is an SO post on it.

Community
  • 1
  • 1
PSL
  • 123,204
  • 21
  • 253
  • 243
2

Try the code below if you are worried about older browsers:

HTML

<input id="user" type="text" placeholder="someone@example.com" /><br />
<input type="password" placeholder="Password" />

JS

(function($){
var placeholderIsSupported = ('placeholder' in document.createElement('input'));
$.fn.emulatePlaceholder = function(){
if(!placeholderIsSupported){
    this.each(function(index, element){
        var handle = $(element);
        var placeholder = handle.attr('placeholder');           
        if(handle.val() == ''){
            handle.val(placeholder);    
        }
        handle.blur(function(e){
            var handle = $(this);
            if(handle.val() == ''){
                handle.val(placeholder);
            }
        });
        handle.focus(function(e){
            var handle = $(this);
            if(handle.val() == placeholder){
                handle.val('');
            }
        });
    });
}
};
})(jQuery);

USAGE

$('input').emulatePlaceholder();

jsFiddle example.

Test the fiddle above in IE<8 to see the code actually working

1

u can use the property placeholder of the tag input