开发者

<input /> type conversion (jQuery)

I have this:

<input type="text" value="Enter Password" class="password" />

... onclick/onfocus, I'd like to change the input type to 'password' and value removed, like so:

<input type="password" value="" class="password" />

This doesn't seem to work:

$('input.password').click(function () {
            $(this).attr('ty开发者_如何学运维pe', 'password');
    });

(See this question for why I want to do this)


This works, but just one problem, I need to click twice to be able to type in the pass field:

var passField = $("input.password");
        var passFieldNew = passField.clone();
        $('input.password').click(function () {
            passFieldNew.attr("type", "password");
            passFieldNew.attr("value", "");
            passFieldNew.insertBefore(passField);
            passField.remove();
        });

how do I fix that problem?

Thanks!


You cannot change the type attr while the element is in the DOM, but if you remove it first you can.

The following should work (tested, but only in firebug). The password class will be kept since it's the same element you insert again.

var $pwd = $('input.password').remove(); // Note, might be better to select on ID
$pwd.attr('type', 'password');
$pwd.val('');
$('#ABC').after($pwd); // Insert it somewhere in the DOM again


What if you had a hidden password field that you swap in for the text field when it get the focus? Something like this (untested):

  <style type="text/css" media="screen">
    #password {
      display: none;
    }
  </style>

  <script type="text/javascript">
    $(document).ready(function() {
      $('#text').focus(function() {
        $(this).hide();
        $('#password').show().focus();
      });
    });
  </script>

  <input type="text" value="Enter Password" class="password" id="text" />
  <input type="password" value="" class="password" id="password" />

When the text field receives focus, it hides itself, shows the password field, and sets the focus to the password field. If you styled the text field and password field to look the same, it should be seamless.


You can't change the type of the input field at runtime, but you can do a crafty switch by replacing it with a new one:

<script type="text/javascript">
$(function()
{
    var password = $("#myPassword").val();
    $("#myPassword").remove();
    $("#form").append('<input id="myPassword" type="text" class="password" />');
    $("#myPassword").val(password);
});
</script>

<div id="form">
    <input id="myPassword" type="password" value="Enter Password" class="password" />
</div>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜