te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - How can you swap an input text field to a password area on focus in JQuery? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can you swap an input text field to a password area on focus in JQuery? - Stack Overflow

programmeradmin3浏览0评论

I would like to display "password" as text in the password area, and when focused the box should bee empty and allow normal password (starred out) input from the user.

Currently I use the following method. Initially I display a text field showing password, when focused it is removed and replaced with a password field. Here is the jQuery:

$(document).ready(function() {
    $("#password").focus( function() {
        $("#pwd").html('<input type="password" id="password" name="password" value="" />');
        $("#password").focus();
    });
});

This works on Firefox and Chrome but fails in IE 8 (and presumably other IE's) as the focus call fails for some reason (maybe the DOM isn't ready?).

A demo is available on jsbin.

Any ideas?

I would like to display "password" as text in the password area, and when focused the box should bee empty and allow normal password (starred out) input from the user.

Currently I use the following method. Initially I display a text field showing password, when focused it is removed and replaced with a password field. Here is the jQuery:

$(document).ready(function() {
    $("#password").focus( function() {
        $("#pwd").html('<input type="password" id="password" name="password" value="" />');
        $("#password").focus();
    });
});

This works on Firefox and Chrome but fails in IE 8 (and presumably other IE's) as the focus call fails for some reason (maybe the DOM isn't ready?).

A demo is available on jsbin.

Any ideas?

Share Improve this question asked Jun 17, 2009 at 23:42 PoolPool 12.3k14 gold badges71 silver badges79 bronze badges 4
  • What if the user has JavaScript off and then type in their password with someone looking over their back? – teh_noob Commented Jun 18, 2009 at 0:44
  • start with a password field then. – nickf Commented Jun 18, 2009 at 0:46
  • 1 This functionality might confuse the user. If I saw a field with the default value "password", I wouldn't expect it to "star out" my input. – Emmett Commented Jun 18, 2009 at 0:47
  • Thanks to everyone for your answers. I personally don't think it's too counterintuitive, a lot of input boxes have special behaviour these days. – Pool Commented Jun 18, 2009 at 11:53
Add a ment  | 

9 Answers 9

Reset to default 6

You could try the watermarker plugin. I don't know if it works in IE8.

After realizing my original solution wouldn't work, I spent a while trying to e up with a working solution just out of curiosity. I'd still remend using the jQuery plugin eKek0 remended, since it degrades better, though.

The following example is fairly flexible. Rather than hard-coding the replacement <input /> tags as strings, the replacement tags are derived from the original tags. This helps if the <input /> tag attributes are altered, since you won't lose any styling or other attributes given to the tags.

The following solution has been tested in Chrome, Firefox, IE8, and IE8 in IE7 patibility mode.

$(document).ready(function() { 

    var focusEvent = function() { 
        if(this.type == 'text') {
            var html = $(this).clone().wrap('<span></span>').parent().html();
            html = html.replace(/type=("|')?text("|')?/, 'type="password"');
            var $newPwdBx = $(html);      

            $(this).replaceWith($newPwdBx);
            $newPwdBx.removeClass('readOnly');
            $newPwdBx.val('');
            $newPwdBx.focus();
            $newPwdBx.blur(blurEvent);
        }
    };

    var blurEvent = function() { 
        if(this.value == '') { 
            var html = $(this).clone().wrap('<span></span>').parent().html();
            html = html.replace(/type=("|')?password("|')?/, 'type="text"');
            var $newTxtBx = $(html);            

            $(this).replaceWith($newTxtBx);
            $newTxtBx.addClass('readOnly');
            $newTxtBx.val('password');
            $newTxtBx.focus(focusEvent);
        } 
    };

    $("#password").focus(focusEvent); 
});

This code replaces the <input /> with the appropriate type on blur and focus. It also adds/removes a class for styling the "password" placeholder text so it is more usable, since the placeholder "password" text is not the default black color, which could potentially be misleading to a user.

You can see it working here: http://jsbin./azugu

I have done something similar to this. If you are set on using javascript, this is one way of doing it:

  • Have two input fields, a normal one and a password one
  • The password is hidden with css
  • When normal input gets focus
    • Hide the normal input
    • Show the password input
    • Give focus to the password input

This approach has some problems to consider. If someone has javascript disabled, or is using the NoScript extension for Firefox, they may not be able to submit the form. If someone starts typing before javascript is loaded, there may be unexpected results.

Another approach is to use css and have javascript as a backup (for IE6). Create an image that has text "Password". Have that image be the background image for the password field. You can use pseudo classes in the css to change the background of the password field for hover and . This way, if a person has javascript disabled, the form still works. It also works as soon as the css is loaded.

The CSS might look something like this:

.pass { 
    background-image: url(/path/to/img.png);
}
.pass:hover {
    background: white;
}

Using jquery the javascript might look something like this:

 $( ".pass" ).hover( function() {
     $( this ).css( "background", "white" );
  };

The most mon way to achieve this is to set a background image to the password field with the text "password" and remove the background image when it gets the focus.

Why not just change the attribute and wipe out the value?

$("#password").focus( function() {
    $(this).attr('type','password');
    $(this).attr('value','');        
});

This works in FF & IE:

$(document).ready(function() {
    $("#password").focus( function() {
        $(this)
          .after('<input type="password" id="password" name="password" value="" />')
          .remove();
        $("#password").focus();
    });
});

Why don't you just put a div over the top?

var $pwd = $("#passwordBox"),
    pos = $pwd.position()
;
$pwd
    .after(  // add the div
        $('<div></div>')
            .html("Password")
            .css({
                position : "absolute",    // place it over this
                top : pos.top + "px",  // adjust as necessary
                left : pos.top + "px"
            })
    )
    .next() // select the new div
    .andSelf()
    .one('click focus', function() {
        $pwd.next().remove()    // remove the div
            .end().focus() // focus the input box
        ;
    })
;

There is also this txReplaceFormPassword plugin made by Simone Lippolis.

Try this, experimentally if you will:

$(document).ready(function() {
    $(".pass").focus(function() {
        $pwInput = $('<input type="password" class="pass" name="password" value="" />');
        $(this).remove();
        $("#someDiv").append($pwInput);
    }).focus();
});
发布评论

评论列表(0)

  1. 暂无评论