Rajyalakshmi
Rajyalakshmi

Reputation: 11

How to perform a click function only the first time in jQuery

I want to create a Form with input fields filled with certain instructions ex: "Enter User name" in the text field of label :"UserName".So that in the first click of the text field the previous statement("Enter User name") should be cleared and cursor should await for an incoming text. On another click of the same text field my new text shuld remain for further submit operations unless it is cleared by me. Hope u got that. This is what we see in various forms.Please help me out as seen as possible. I want d task done using jQuery...

Upvotes: 1

Views: 171

Answers (3)

Blair McMillan
Blair McMillan

Reputation: 5349

HTML5 gives you a placeholder attribute that does what you want. Which you may as well implement as well. Other terms to search for other than watermark (as Darin suggests) is jquery placeholder and jquery defaultvalue.

Upvotes: 0

RobertPitt
RobertPitt

Reputation: 57268

i would do something like

$(document).ready(function(){
    $('#myForm input[type=text]').each(function(){
        initialValue = $(this).value();

        //Bind the data to the element
        $(this).data('initialValue',initialValue);

        //Bind an focus event to it
        $(this).focus(function(){
            //In
            if($(this).value() == $(this).data('initialValue')){
                //Remove
                $(this).value("")
            };
        },
        function(){
            if($(this).value() == ""){
                //Restore
                $(this).value($(this).data('initialValue'))
            };
        })
    });
});

So what this is doing is finding your form and for each input element thats "type=text" it will get the initial value and store it, then set to events focusin and focusout to watch out for the user.

when the user focus'es in it checks to see what the value is, and if its the same value as what it was at the start it will set the text to nothing.

and when a user focus'es out it would restore the initial value IF the value is empty.

Hope this will put you on right track mate.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

There's a nice jquery watermark plugin. You may also try one of the others.

Upvotes: 2

Related Questions