Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a text watermark in a password field?

Tags:

html

jquery

I want a watermark in my password field which says "Password".

Here is my code:
jquery:

$(document).ready(function() {

    var watermark = 'Password';

    //init, set watermark text and class
    $('#input_pwd').val(watermark).addClass('watermark');

    //if blur and no value inside, set watermark text and class again.
    $('#input_pwd').blur(function(){
        if ($(this).val().length == 0){
            $(this).val(watermark).addClass('watermark');
        }
    });

    //if focus and text is watermrk, set it to empty and remove the watermark class
    $('#input_pwd').focus(function(){
        if ($(this).val() == watermark){
            $(this).val('').removeClass('watermark');
        }
    });
});

html:

<input class="ui_input" id="input_pwd" type="password" name="pass" id="pass" style="height:25px; width:250px; font-size:14px;" required />

My jsfiddle: click here


edit: I prefer jquery :)

edit: Our brother Konrad Gadzina has given me what I was looking for but thanks for all your efforts everyone!

like image 747
Surfine Avatar asked Dec 04 '22 11:12

Surfine


2 Answers

You can set the type to be text by default and change it to password with JS while removing watermark class.

HTML:

<input class="ui_input" id="input_pwd" type="text" name="pass" id="pass" style="height:25px; width:250px; font-size:14px;" required />

JS:

    //if blur and no value inside, set watermark text and class again.
    $('#input_pwd').blur(function(){
        if ($(this).val().length == 0){
            $(this).val(watermark).addClass('watermark');
            $(this).attr('type', 'text');
        }
    });

    //if focus and text is watermrk, set it to empty and remove the watermark class
    $('#input_pwd').focus(function(){
        if ($(this).val() == watermark){
            $(this).val('').removeClass('watermark');
            $(this).attr('type', 'password');
        }
    });

Check fiddle - http://jsfiddle.net/w4Hh4/1/

like image 160
Konrad Gadzina Avatar answered Jan 08 '23 15:01

Konrad Gadzina


Use html's placeholder

<input class="ui_input" id="input_pwd" type="password" name="pass" id="pass" style="height:25px; width:250px; font-size:14px;" placeholder='Password' required />

And you don't need any js for it.

NOTE: The placeholder attribute is supported in Internet Explorer 10, Firefox, Opera, Chrome, and Safari. Unfortunatly as stated in the comments it won't work for older IE

like image 43
Spokey Avatar answered Jan 08 '23 16:01

Spokey