如果密码字段为空,则为Jquery

时间:2011-05-09 19:47:20

标签: javascript jquery html forms input

我正在尝试将可见文本添加到“输入密码”的密码字段中,然后单击文本清除并键入点。我有两个输入类型= text和另一个密码。密码输入在开始时隐藏,但在您使用“输入密码”指令单击输入后出现。

它执行此操作http://mudge.github.com/jquery_example/但我正在尝试将其用于密码字段。

HTML

<input type="text" id="password_instructions" />
<input type="password" id="password" /> 

Jquery

        var $password = $('#password');
        $password.hide(); //hide input with type=password

        $("#password_instructions").click(function() {
                $( this ).hide();
                $('#password').show();
                $('#password').focus();

                if ($password.val().length === 0) { //if password field is empty            
                    $password.focusout(function() { //when clicking outside empty password input
                        $( this ).hide();
                        $('#password_default_value').show();
                        $('#password_instructions').default_value('Enter a password'); //will clear on click
                    });                     
                }
        });

什么行不通:

当您填写密码输入(出现点)并单击时,隐藏输入并显示#password_instruction输入。所以它不尊重if empty语句。由于某种原因,即使我输入了密码,它也会将输入视为空。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:9)

在调用focus()之后,您似乎期待某种“暂停”,并且只有当最终用户以某种方式输入密码时才会执行JS代码的剩余部分。

事实并非如此。该功能一次性完全执行。

您需要移动以下内容

        if ($password.val().length === 0) { //if password field is empty            
            $password.focusout(function() { //when clicking outside password input
                $(this).hide();
                $('#password_default_value').show();
                $('#password_instructions').default_value('Enter a password'); //will clear on click
            });                     
        }

进入另一个独立功能:

$('#password').focusout(function() {
    if ($(this).val().length === 0) { //if password field is empty            
        $(this).hide();
        $('#password_default_value').show();
        $('#password_instructions').default_value('Enter a password'); //will clear on click
    }
});

答案 1 :(得分:3)

你的意思是:

<input type="password" placeholder="enter password">

如果您希望为旧版浏览器实现此功能,则必须将支票移至onBlur事件。在jQuery中,这看起来像:

$('#password').blur(function() {
    if ($password.val().length === 0) { //if password field is empty            
        $password.focusout(function() { //when clicking outside password input
            $( this ).hide();
            $('#password_default_value').show();
            $('#password_instructions').default_value('Enter a password'); //will clear on click
        });                     
    }
});