开发者

jQuery blur/focus strange situation

I have input with password type. And I want to do simple thing. If input isn't in focus, input has default value. I try to do it with jQuery. My HTML:

<input type="password" name="password" id="password" defvalue="password" class="filling-password">

My Javascript(jQuery):

$('.filling-password').each(function(){
    var b = $(this);
    var id = this.id;
    var val = b.attr("defvalue");
    var textInput = '<input id="'+id+'-text" type="text" value="'+val+'">';
    $(textInput).insertAfter(t开发者_StackOverflowhis);
    b.hide(0);
    $("#"+id+"-text").focus(function(){
        $(this).hide(0);
        b.show(0).focus();
    });
    b.blur(function(){
        if ($(this).val() == "") {
            $(textInput).insertAfter(this);
            b.hide(0);
        }
    });
});

All work nice. But only one time. When I click first time input become empty, when I blur input have default value.

But If I click third time nothing happen. What is wrong? Or maybe there are better ways to do this?


Here's one way roughly as you described it, inserted inside $(function() { ... }); of course (live demo):

$('.filling-password').each(function() {
    var pass = $(this),
        text = $('<input type="text"/>').val(pass.attr('defvalue'));

    text.insertBefore(pass).focus(function() {
        text.hide();
        pass.show().focus();
    });

    pass.hide().blur(function() {
        if (pass.val() == '') {
            pass.hide();
            text.show();
        }
    });
});

Possibly better is to overlay a label on top of the text box (live demo):

$('.filling-password').each(function() {
    var pass = $(this),
        div = pass.wrap('<div/>').parent(),
        label = $('<label/>').attr('for', pass.attr('id')).text(pass.attr('defvalue')).prependTo(div);

    div.css({
        display: 'inline',
        position: 'relative'
    });

    label.css({
        color: '#666',
        fontSize: '12px',
        position: 'absolute',
        left: '4px',
        bottom: '2px'
    });

    pass.focus(function() {
        label.hide();
    }).blur(function() {
        if(pass.val() == '') {
            label.show();
        }
    });

There's a jQuery plug-in that implements the latter approach more nicely.


I don't know jQuery but judging your code, this is the direction you want to go:

$('.filling-password').each(function(){

    var value = $(this).attr('value');
    var defaultvalue = 'password';


    $(this).blur(function() {

        if($(this).val() === '') $(this).value = defaultvalue;
    });


    $(this).focus(function() {

         if($(this).val() === defaultvalue) $(this).value = '';
    });
});

And for the HTML, the defvalue attribute is not valid I believe:

<input type="password" name="password" id="password" value="password" class="filling-password">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜