用jQuery改变input字段的types

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

这应该将id="password" typeinput字段( id="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> 

作为浏览器安全模型的一部分,这种行为很可能被阻止。

编辑:的确,现在在Safari中testing,我得到的错误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'; 

编辑3:直接从jQuery源代码,这似乎与IE相关(可能是一个错误或其安全模型的一部分,但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"; 

更简单…没有必要创build所有的dynamic元素。 只需创build两个单独的字段,使“真实”密码字段(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()" /> 

所以当用户进入“假”密码字段时,它将被隐藏,真实的字段将被显示,并且焦点将移动到真实的字段。 他们将永远无法在假字段中input文字。

当用户离开真正的密码字段时,脚本将会看到它是否为空,如果是这样,将隐藏真实的字段并显示假的字段。

请注意不要在两个input元素之间留出空格,因为IE会将一个位置放在另一个位置(呈现空间)之后,当用户input/退出时,该字段将显示为移动。

一步解决scheme

 $('#password').get(0).type = 'text'; 

现在,你可以使用

 $("#password").prop("type", "text"); 

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

 <input type="password" placeholder="Password" /> 

在所有,但IE浏览器。 在那里有占位符垫片来模仿在IE中的function。

更多的跨浏览器解决scheme…我希望这能帮助那里的人。

这个解决scheme尝试设置type属性,如果失败,它只是创build一个新的<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; } } 

这对我有用。

 $('#password').replaceWith($('#password').clone().attr('type', 'text')); 

一个使用jQuery的最终方法:


将原始input字段保留在屏幕上。

 $("#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 

用JavaScript创build新的input字段。

 var new_input = document.createElement("input"); 

将ID和值从隐藏的input字段迁移到新的input字段。

 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 

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

将点击/焦点/更改事件附加到新的input元素,以便在隐藏的input上触发相同的事件。

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

旧的隐藏input元素仍然在DOM内部,所以会对由新input元素触发的事件作出反应。 当ID被交换时,新的input元素将像旧的那样起作用并响应对旧的隐藏的inputID的任何函数调用,但看起来不同。

有点棘手,但工作! 😉

我没有在IE中testing(因为我需要这个iPad的网站) – 一种forms,我不能改变的HTML,但我可以添加JS:

 document.getElementById('phonenumber').type = 'tel'; 

(老派的JS在所有jQuery旁边都很难看!)

但是, http : //bugs.jquery.com/ticket/1957链接到MSDN:“从Microsoft Internet Explorer 5开始,type属性是可读/可写的,但只有在使用createElement方法创buildinput元素时在它被添加到文档之前“。 所以也许你可以复制元素,改变types,添加到DOM,并删除旧的?

你有没有尝试使用.prop()?

 $("#password").prop('type','text'); 

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

只需创build一个新的字段来绕过这个安全的事情:

 var $oldPassword = $("#password"); var $newPassword = $("<input type='text' />") .val($oldPassword.val()) .appendTo($oldPassword.parent()); $oldPassword.remove(); $newPassword.attr('id','password'); 

我在尝试在Firefox 5中执行此操作时收到相同的错误消息。

我使用下面的代码解决了它:

 <script type="text/javascript" language="JavaScript"> $(document).ready(function() { var passfield = document.getElementById('password_field_id'); passfield.type = 'text'; }); function focusCheckDefaultValue(field, type, defaultValue) { if (field.value == defaultValue) { field.value = ''; } if (type == 'pass') { field.type = 'password'; } } function blurCheckDefaultValue(field, type, defaultValue) { if (field.value == '') { field.value = defaultValue; } if (type == 'pass' && field.value == defaultValue) { field.type = 'text'; } else if (type == 'pass' && field.value != defaultValue) { field.type = 'password'; } } </script> 

要使用它,只需将字段的onFocus和onBlur属性设置为如下所示:

 <input type="text" value="Username" name="username" id="username" onFocus="javascript:focusCheckDefaultValue(this, '', 'Username -OR- Email Address');" onBlur="javascript:blurCheckDefaultValue(this, '', 'Username -OR- Email Address');"> <input type="password" value="Password" name="pass" id="pass" onFocus="javascript:focusCheckDefaultValue(this, 'pass', 'Password');" onBlur="javascript:blurCheckDefaultValue(this, 'pass', 'Password');"> 

我也使用这个用户名字段,所以它切换默认值。 当你调用它时,只需将函数的第二个参数设置为“”。

也可能值得注意的是,我的密码字段的默认types实际上是密码,以防万一用户没有启用javascript或者出现问题,这样他们的密码仍然受到保护。

$(document).ready函数是jQuery,并在文档加载完成时加载。 然后这将密码字段更改为文本字段。 显然你必须改变'password_field_id'到你的密码字段的ID。

随意使用和修改代码!

希望这有助于每个人都有同样的问题,我:)

– CJ肯特

编辑:好的解决scheme,但不是绝对的。 在FF8和IE8上工作,但不完全在Chrome上(16.0.912.75版本)。 Chrome在加载页面时不显示密码文本。 另外 – 开启自动填充function时,FF将显示您的密码。

适用于所有需要所有浏览器function的用户的简单解决scheme:

HTML

 <input type="password" id="password"> <input type="text" id="passwordHide" style="display:none;"> <input type="checkbox" id="passwordSwitch" checked="checked">Hide password 

jQuery的

 $("#passwordSwitch").change(function(){ var p = $('#password'); var h = $('#passwordHide'); h.val(p.val()); if($(this).attr('checked')=='checked'){ h.hide(); p.show(); }else{ p.hide(); h.show(); } }); 

types属性无法更改,您需要使用文本inputreplace或覆盖input,并在提交时将值发送到密码input。

尝试这个
演示在这里

 $(document).delegate('input[type="text"]','click', function() { $(this).replaceWith('<input type="password" value="'+this.value+'" id="'+this.id+'">'); }); $(document).delegate('input[type="password"]','click', function() { $(this).replaceWith('<input type="text" value="'+this.value+'" id="'+this.id+'">'); }); 

使用这个很容易

 <input id="pw" onclick="document.getElementById('pw').type='password'; document.getElementById('pw').value='';" name="password" type="text" value="Password" /> 
 $('#pass').focus(function() { $('#pass').replaceWith("<input id='password' size='70' type='password' value='' name='password'>"); $('#password').focus(); }); <input id='pass' size='70' type='text' value='password' name='password'> 
 jQuery.fn.outerHTML = function() { return $(this).clone().wrap('<div>').parent().html(); }; $('input#password').replaceWith($('input.password').outerHTML().replace(/text/g,'password')); 

这将做的伎俩。 尽pipe可以改进以忽略现在不相关的属性。

插入:

 (function($){ $.fn.changeType = function(type) { return this.each(function(i, elm) { var newElm = $("<input type=\""+type+"\" />"); for(var iAttr = 0; iAttr < elm.attributes.length; iAttr++) { var attribute = elm.attributes[iAttr].name; if(attribute === "type") { continue; } newElm.attr(attribute, elm.attributes[iAttr].value); } $(elm).replaceWith(newElm); }); }; })(jQuery); 

用法:

 $(":submit").changeType("checkbox"); 

小提琴:

http://jsfiddle.net/joshcomley/yX23U/

简单地说:

 this.type = 'password'; 

 $("#password").click(function(){ this.type = 'password'; }); 

这是假设您的input字段被手动设置为“文本”。

这是一个小小的片段,允许您更改文档中元素的type

jquery.type.js ( GitHub Gist ):

 var rtype = /^(?:button|input)$/i; jQuery.attrHooks.type.set = function(elem, value) { // We can't allow the type property to be changed (since it causes problems in IE) if (rtype.test(elem.nodeName) && elem.parentNode) { // jQuery.error( "type property can't be changed" ); // JB: Or ... can it!? var $el = $(elem); var insertionFn = 'after'; var $insertionPoint = $el.prev(); if (!$insertionPoint.length) { insertionFn = 'prepend'; $insertionPoint = $el.parent(); } $el.detach().attr('type', value); $insertionPoint[insertionFn]($el); return value; } else if (!jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input")) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute("type", value); if (val) { elem.value = val; } return value; } } 

它通过从文档中删除input ,更改type然后将其放回原来的位置来解决问题。

请注意,此代码段仅针对WebKit浏览器进行了testing – 没有任何其他保证!

我猜你可以使用包含“password”这个单词的背景图像,并将其改回到.focus()的空白背景图像。

.blur() —->图像与“密码”

.focus() —–>没有“密码”的图像

你也可以用一些CSS和jQuery来做。 有一个文本字段正好显示在密码字段的顶部,hide()是在焦点()和焦点在密码字段…

它的工作更容易:

 document.querySelector('input[type=password]').setAttribute('type', 'text'); 

并且为了再次将其返回到密码字段( 假设密码字段是具有文本types的第二input标签 ):

 document.querySelectorAll('input[type=text]')[1].setAttribute('type', 'password') 

我喜欢这种方式,来改变一个input元素的types:old_input.clone()….这里是一个例子。 有一个checkbox“id_select_multiple”。 如果这是更改为“选定”,名称为“foo”的input元素应更改为checkbox。 如果没有检查,他们应该再次成为单选button。

  $(function() { $("#id_select_multiple").change(function() { var new_type=''; if ($(this).is(":checked")){ // .val() is always "on" new_type='checkbox'; } else { new_type="radio"; } $('input[name="foo"]').each(function(index){ var new_input = $(this).clone(); new_input.attr("type", new_type); new_input.insertBefore($(this)); $(this).remove(); }); } )}); 

inheritance人一个DOM解决scheme

 myInput=document.getElementById("myinput"); oldHtml=myInput.outerHTML; text=myInput.value; newHtml=oldHtml.replace("password","text"); myInput.outerHTML=newHtml; myInput=document.getElementById("myinput"); myInput.value=text; 

我创build了一个jQuery扩展来切换文本和密码。 在IE8中工作(可能6&7以及,但没有testing),不会失去你的价值或属性:

 $.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 = $('<input type="password" />'); }else if((showPass == null && ($this.attr('type') == 'password')) || (showPass != null && showPass)){ clone = $('<input type="text" />'); } $.each($this.prop("attributes"), function() { if(this.name != 'type') { clone.attr(this.name, this.value); } }); clone.val($this.val()); $this.replaceWith(clone); } }); }; 

奇迹般有效。 你可以直接调用$('#element').togglePassword(); 在两者之间切换,或给出一个选项来强制基于其他内容的操作(如checkbox): $('#element').togglePassword($checkbox.prop('checked'));

这是一种方法,使用密码字段旁边的图像来查看密码(文本input)和不看(密码input)之间切换。 我用“睁眼”和“闭眼”的形象,但是你可以使用任何适合你的东西。 它的工作方式是有两个input/图像,并在点击图像时,将值从可见input复制到隐藏的图像,然后交换其可见性。 与使用硬编码名称的许多其他答案不同,这个通用性足以在页面上多次使用。 如果JavaScript不可用,它也会降级。

以下是这些在页面上的两个样子。 在这个例子中,密码-A已经通过点击它的眼睛显示出来。

它看起来如何

 $(document).ready(function() { $('img.eye').show(); $('span.pnt').on('click', 'img', function() { var self = $(this); var myinp = self.prev(); var myspan = self.parent(); var mypnt = myspan.parent(); var otspan = mypnt.children().not(myspan); var otinp = otspan.children().first(); otinp.val(myinp.val()); myspan.hide(); otspan.show(); }); }); 
 img.eye { vertical-align: middle; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form> <b>Password-A:</b> <span class="pnt"> <span> <input type="password" name="passa"> <img src="eye-open.png" class="eye" alt="O" style="display:none"> </span> <span style="display:none"> <input type="text"> <img src="eye-closed.png" class="eye" alt="*"> </span> </span> </form> <form> <b>Password-B:</b> <span class="pnt"> <span> <input type="password" name="passb"> <img src="eye-open.png" class="eye" alt="O" style="display:none"> </span> <span style="display:none"> <input type="text"> <img src="eye-closed.png" class="eye" alt="*"> </span> </span> </form>