使用jQuery更改输入字段的类型

Ric*_*nop 200 javascript jquery html-input

$(document).ready(function() {
    // #login-box password field
    $('#password').attr('type', 'text');
    $('#password').val('Password');
});
Run Code Online (Sandbox Code Playgroud)

这应该更改正常文本字段的#password输入字段(with id="password"),type password然后填写文本"Password".

但它不起作用.为什么?

这是表格:

<form enctype="application/x-www-form-urlencoded" method="post" action="/auth/sign-in">
  <ol>
    <li>
      <div class="element">
        <input type="text" name="username" id="username" value="Prihlasovacie meno" class="input-text" />
      </div>
    </li>
    <li>
      <div class="element">
        <input type="password" name="password" id="password" value="" class="input-text" />
      </div>
    </li>
    <li class="button">
      <div class="button">
        <input type="submit" name="sign_in" id="sign_in" value="Prihlási?" class="input-submit" />
      </div>
    </li>
  </ol>
</form>
Run Code Online (Sandbox Code Playgroud)

eye*_*ess 256

作为浏览器安全模型的一部分,很可能会阻止此操作.

编辑:确实,现在在Safari中测试,我收到了错误type property cannot be changed.

编辑2:这似乎是jQuery中的一个错误.使用以下直接DOM代码可以正常工作:

var pass = document.createElement('input');
pass.type = 'password';
document.body.appendChild(pass);
pass.type = 'text';
pass.value = 'Password';
Run Code Online (Sandbox Code Playgroud)

编辑3:直接来自jQuery源代码,这似乎与IE有关(可能是一个bug或其安全模型的一部分,但jQuery并不具体):

// We can't allow the type property to be changed (since it causes problems in IE)
if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
    throw "type property can't be changed";
Run Code Online (Sandbox Code Playgroud)

  • 必须说,这是我见过的最无用的安全测量.在快速更改字段类型和用全新字段替换它之间似乎没有那么大的区别.非常奇怪......无论如何,为我工作.谢谢! (12认同)
  • 这是有道理的.jQuery没有任何问题. (2认同)
  • 它不是安全模型的东西,我可以确认它在IE7中不起作用,IE8有错误:无法获取type属性 (2认同)
  • @Michael,我建议不要直接改变jQuery.除此之外,它还会产生冲突责任,这种检查可能是有原因的.如果您不需要担心IE支持,您可以改为实现与`attr`并行的jQuery扩展,但允许更改`input`元素的`type`属性. (2认同)

小智 76

更容易......没有必要创建所有动态元素.只需创建两个单独的字段,一个是"真正的"密码字段(type ="password"),另一个是"假"密码字段(type ="text"),将假字段中的文本设置为浅灰色并且将初始值设置为"密码".然后用jQuery添加几行Javascript,如下所示:

    <script type="text/javascript">

        function pwdFocus() {
            $('#fakepassword').hide();
            $('#password').show();
            $('#password').focus();
        }

        function pwdBlur() {
            if ($('#password').attr('value') == '') {
                $('#password').hide();
                $('#fakepassword').show();
            }
        }
    </script>

    <input style="color: #ccc" type="text" name="fakepassword" id="fakepassword" value="Password" onfocus="pwdFocus()" />
    <input style="display: none" type="password" name="password" id="password" value="" onblur="pwdBlur()" />
Run Code Online (Sandbox Code Playgroud)

因此,当用户输入"假"密码字段时,它将被隐藏,真实字段将被显示,焦点将移动到真实字段.他们永远无法在假场中输入文字.

当用户离开真实密码字段时,脚本将看到它是否为空,如果是,则将隐藏真实字段并显示虚假字段.

注意不要在两个输入元素之间留一个空格,因为IE将一个接一个地放置一个(渲染空间),当用户进入/退出时,该字段将显示为移动.

  • 您也可以链接以下函数:`$('#password').show(); $('#password').focus();`as` $('#password').show().focus();` (2认同)

San*_*ahu 73

一步解决方案

$('#password').get(0).type = 'text';
Run Code Online (Sandbox Code Playgroud)

  • 甚至更短的一个,$('#password')[0] .type ='text'; (16认同)
  • `document.getElementById`应该足够了,你不需要jQuery!;-) (4认同)
  • 实际上,根据问题,它是jQuery解决方案。 (2认同)
  • 这可能会导致IE9出现问题,类型未定义.非常适合其他浏览器. (2认同)

And*_*rew 39

如今,你可以使用

$("#password").prop("type", "text");
Run Code Online (Sandbox Code Playgroud)

但是,当然,你应该真的这样做

<input type="password" placeholder="Password" />
Run Code Online (Sandbox Code Playgroud)

除了IE之外的所有.有占位符垫片在那里模仿IE中的功能.


BMi*_*ner 14

一个更加跨浏览器的解决方案......我希望这一点可以帮助那些人.

此解决方案尝试设置type属性,如果失败,则只创建一个新<input>元素,保留元素属性和事件处理程序.

changeTypeAttr.js(GitHub Gist):

/* x is the <input/> element
   type is the type you want to change it to.
   jQuery is required and assumed to be the "$" variable */
function changeType(x, type) {
    x = $(x);
    if(x.prop('type') == type)
        return x; //That was easy.
    try {
        return x.prop('type', type); //Stupid IE security will not allow this
    } catch(e) {
        //Try re-creating the element (yep... this sucks)
        //jQuery has no html() method for the element, so we have to put into a div first
        var html = $("<div>").append(x.clone()).html();
        var regex = /type=(\")?([^\"\s]+)(\")?/; //matches type=text or type="text"
        //If no match, we add the type attribute to the end; otherwise, we replace
        var tmp = $(html.match(regex) == null ?
            html.replace(">", ' type="' + type + '">') :
            html.replace(regex, 'type="' + type + '"') );
        //Copy data from old element
        tmp.data('type', x.data('type') );
        var events = x.data('events');
        var cb = function(events) {
            return function() {
                //Bind all prior events
                for(i in events)
                {
                    var y = events[i];
                    for(j in y)
                        tmp.bind(i, y[j].handler);
                }
            }
        }(events);
        x.replaceWith(tmp);
        setTimeout(cb, 10); //Wait a bit to call function
        return tmp;
    }
}
Run Code Online (Sandbox Code Playgroud)


ste*_*uss 8

这适合我.

$('#password').replaceWith($('#password').clone().attr('type', 'text'));
Run Code Online (Sandbox Code Playgroud)


Ash*_*hab 7

这对我有用。

$('#newpassword_field').attr("type", 'text');
Run Code Online (Sandbox Code Playgroud)


Ken*_*ega 6

使用jQuery的终极方法:


保持原始输入字段隐藏在屏幕上.

$("#Password").hide(); //Hide it first
var old_id = $("#Password").attr("id"); //Store ID of hidden input for later use
$("#Password").attr("id","Password_hidden"); //Change ID for hidden input
Run Code Online (Sandbox Code Playgroud)

通过JavaScript动态创建新的输入字段.

var new_input = document.createElement("input");
Run Code Online (Sandbox Code Playgroud)

将ID和值从隐藏输入字段迁移到新输入字段.

new_input.setAttribute("id", old_id); //Assign old hidden input ID to new input
new_input.setAttribute("type","text"); //Set proper type
new_input.value = $("#Password_hidden").val(); //Transfer the value to new input
$("#Password_hidden").after(new_input); //Add new input right behind the hidden input
Run Code Online (Sandbox Code Playgroud)

为了解决IE上的错误type property cannot be changed,您可能会发现这有用如下:

将click/focus/change事件附加到新的input元素,以便在隐藏的输入上触发相同的事件.

$(new_input).click(function(){$("#Password_hidden").click();});
//Replicate above line for all other events like focus, change and so on...
Run Code Online (Sandbox Code Playgroud)

旧的隐藏输入元素仍然在DOM内部,因此将与新输入元素触发的事件作出反应.当ID被交换时,新的输入元素将像旧的一样,并响应任何函数调用旧的隐藏输入的ID,但看起来不同.

有点棘手,但工作!;-)


Mar*_*vie 5

您是否尝试过使用.prop()?

$("#password").prop('type','text');
Run Code Online (Sandbox Code Playgroud)

http://api.jquery.com/prop/