user1427811
user1427811

Reputation:

default text change into input text with jQuery

I have a simple form with three input text with a different value for each. I want when I click inside at one to clear the deafult value and when I go out to put the default text into the input if the user doesn't insert a text. I have write a code in jQuery the problem is when I click out it takes the same default value of the first input type and not its text why? This is the code:

<script type="text/javascript">
$(document).ready(function() {
    $('.testo').each(function() {
    var default_value = this.value;
        $(".testo").focus(function() {
            $(this).attr('value','');
        });
        $(".testo").blur(function() {
            if ($(this).attr('value')==''){
                $(this).attr('value',default_value);
            }
        });
    });
});

<p><input type="text" name="nome" class="testo"  value="Nome e Cognome"/> </p>
            <p><input type="text" name="telefono" class="testo" value="un tuo Recapito Telefonico"/></p>
            <p><input type="text" name="email"  class="testo" maxlength="60" value="una E-Mail Valida"/></p>

Upvotes: 1

Views: 535

Answers (3)

davids
davids

Reputation: 6371

You could achieve this without javascript, using the placeholder attribute of the input:

<input type="text" name="telefono" class="testo" placeholder="un tuo Recapito Telefonico"/>

Find an example here

EDIT:

Have in account that this is html5 and, although it's quite widely supported by browsers, if you want to support them all, you should follow @liam's approach.

Upvotes: 5

xdazz
xdazz

Reputation: 160833

The working demo.

$(document).ready(function() {
    $('.testo').each(function() {
        var default_value = this.value;
        // you could do chain method to avoid call $(this) twice.
        $(this).focus(function() {
            $(this).val('');
        }).blur(function() {
            if ($(this).val() == ''){
                $(this).val(default_value);
            }
        });
    });
});​

Upvotes: 0

Liam
Liam

Reputation: 29674

your javascript isn't using the same value each time you bind the focus and blur events. so these will always bind to the last in the each, try:

$(document).ready(function() {
    $('.testo').each(function() {
    var default_value = this.value;
        $(this).focus(function() {
            $(this).val('');
        });
        $(this).blur(function() {
            if ($(this).val()==''){
                $(this).val(default_value);
            }
        });
    });
});

Upvotes: 1

Related Questions