change type of input field with jQuery

后端 未结 29 2612
青春惊慌失措
青春惊慌失措 2020-11-22 05:13
$(document).ready(function() {
    // #login-box password field
    $(\'#password\').attr(\'type\', \'text\');
    $(\'#passwo         


        
29条回答
  •  不知归路
    2020-11-22 05:35

    I've created a jQuery extension to toggle between text and password. Works in IE8 (probably 6&7 as well, but not tested) and won't lose your value or attributes:

    $.fn.togglePassword = function (showPass) {
        return this.each(function () {
            var $this = $(this);
            if ($this.attr('type') == 'text' || $this.attr('type') == 'password') {
                var clone = null;
                if((showPass == null && ($this.attr('type') == 'text')) || (showPass != null && !showPass)) {
                    clone = $('');
                }else if((showPass == null && ($this.attr('type') == 'password')) || (showPass != null && showPass)){
                    clone = $('');
                }
                $.each($this.prop("attributes"), function() {
                    if(this.name != 'type') {
                        clone.attr(this.name, this.value);
                    }
                });
                clone.val($this.val());
                $this.replaceWith(clone);
            }
        });
    };
    

    Works like a charm. You can simply call $('#element').togglePassword(); to switch between the two or give an option to 'force' the action based on something else (like a checkbox): $('#element').togglePassword($checkbox.prop('checked'));

提交回复
热议问题