提问人:Richard Knop 提问时间:10/9/2009 最后编辑:Rory O'KaneRichard Knop 更新时间:10/17/2023 访问量:394266
使用 jQuery 更改输入字段的类型
change type of input field with jQuery
问:
$(document).ready(function() {
// #login-box password field
$('#password').attr('type', 'text');
$('#password').val('Password');
});
这应该将输入字段(with)更改为普通文本字段,然后填写文本“密码”。#password
id="password"
type
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中进行测试,我收到错误.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";
评论
attr
type
input
只需创建一个新字段来绕过此安全操作:
var $oldPassword = $("#password");
var $newPassword = $("<input type='text' />")
.val($oldPassword.val())
.appendTo($oldPassword.parent());
$oldPassword.remove();
$newPassword.attr('id','password');
无法更改类型属性,您需要用文本输入替换或覆盖输入,并在提交时将值发送到密码输入。
使用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
通过 JavaScript 动态创建新的输入字段。
var new_input = document.createElement("input");
将 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
要解决IE上的错误,您可能会发现这很有用,如下所示:type property cannot be changed
将单击/焦点/更改事件附加到新的输入元素,以便在隐藏输入上触发相同的事件。
$(new_input).click(function(){$("#Password_hidden").click();});
//Replicate above line for all other events like focus, change and so on...
旧的隐藏输入元素仍在 DOM 中,因此将与新输入元素触发的事件做出反应。当 ID 被交换时,新的输入元素将像旧元素一样工作,并响应对旧隐藏输入的 ID 的任何函数调用,但看起来不同。
有点棘手,但有效!!;-)
更简单...无需创建所有动态元素。只需创建两个单独的字段,一个是“真实”密码字段(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()" />
因此,当用户输入“假”密码字段时,它将被隐藏,显示真实字段,焦点将移动到真实字段。他们永远无法在虚假字段中输入文本。
当用户离开真实密码字段时,脚本将查看它是否为空,如果是,则隐藏真实字段并显示假字段。
注意不要在两个输入元素之间留有空格,因为 IE 会稍微放置一个元素(呈现空间),并且当用户进入/退出该字段时,该字段将显示为移动。
评论
$('#password').show(); $('#password').focus();
$('#password').show().focus();
我没有在 IE 中进行测试(因为我需要这个用于 iPad 站点) - 我无法更改 HTML 但我可以添加 JS 的表单:
document.getElementById('phonenumber').type = 'tel';
(老派的JS在所有jQuery旁边都很丑陋!
但是,http://bugs.jquery.com/ticket/1957 链接到 MSDN:“从 Internet Explorer 5 Microsoft开始,type 属性是读/写一次,但仅在使用 createElement 方法创建输入元素时,并且将其添加到文档之前。 所以也许你可以复制元素,更改类型,添加到DOM并删除旧的元素?
使用这个非常容易
<input id="pw" onclick="document.getElementById('pw').type='password';
document.getElementById('pw').value='';"
name="password" type="text" value="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');">
我也将其用于用户名字段,因此它会切换默认值。只需在调用函数时将函数的第二个参数设置为“”即可。
另外,值得注意的是,我的密码字段的默认类型实际上是密码,以防万一用户没有启用javascript或出现问题,这样他们的密码仍然受到保护。
$(document).ready 函数是 jQuery,在文档完成加载时加载。然后,这会将密码字段更改为文本字段。显然,您必须将“password_field_id”更改为密码字段的 ID。
随意使用和修改代码!
希望这能帮助到所有遇到我:)相同问题的人
-- CJ肯特
编辑: 好的解决方案,但不是绝对的。适用于 FF8 和 IE8,但不能完全适用于 Chrome(16.0.912.75 版本)。Chrome 在网页加载时不会显示密码文本。 另外 - 当自动填充打开时,FF 将显示您的密码。
我喜欢这种方式,更改输入元素的类型:old_input.clone().... 下面是一个示例。有一个复选框“id_select_multiple”。如果将其更改为“selected”,则名称为“foo”的输入元素应更改为复选框。如果未选中,它们应该再次成为单选按钮。
$(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();
});
}
)});
评论
$('#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'>
这是一个小片段,允许您更改文档中的元素。type
jquery.type.js
(GitHub 要点):
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 浏览器进行了测试,不能保证其他任何内容!
评论
delete jQuery.attrHooks.type
一步到位的解决方案
$('#password').get(0).type = 'text';
评论
document.getElementById
应该足够了,你不需要jQuery!;-)
一个更跨浏览器的解决方案...我希望这句话的要点能帮助到那里的人。
此解决方案尝试设置属性,如果失败,则仅创建一个新元素,保留元素属性和事件处理程序。type
<input>
changeTypeAttr.js
(GitHub 要点):
/* 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;
}
}
评论
jQuery.fn.outerHTML = function() {
return $(this).clone().wrap('<div>').parent().html();
};
$('input#password').replaceWith($('input.password').outerHTML().replace(/text/g,'password'));
这将解决问题。尽管可以改进以忽略现在不相关的属性。
插件:
(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/
我想您可以使用包含单词“password”的背景图像并将其更改回空的背景图像。.focus()
.blur()
---->带有“密码”的图像
.focus()
没有“密码”的----->图像
你也可以用一些CSS和jQuery来做到这一点。让文本字段正好显示在密码字段的顶部,hide() 位于 focus() 上,然后专注于密码字段......
简单地说:
this.type = 'password';
如
$("#password").click(function(){
this.type = 'password';
});
这是假设您的输入字段事先设置为“文本”。
对于所有想要在所有浏览器中使用功能的人来说,这是一个简单的解决方案:
[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();
}
});
这对我有用。
$('#password').replaceWith($('#password').clone().attr('type', 'text'));
评论
如今,您只需使用
$("#password").prop("type", "text");
但是,当然,你真的应该这样做
<input type="password" placeholder="Password" />
在除 IE 之外的所有产品中。在IE中也有占位符填充码来模拟该功能。
评论
placeholder=“Password”
的 jsFiddle 演示。属性上的 HTML 规范和 MDN。占位符
的 JavaScript 填充码。placeholder
这是一个 DOM 解决方案
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;
你试过使用 .prop() 吗?
$("#password").prop('type','text');
评论
我创建了一个jQuery扩展来在文本和密码之间切换。适用于 IE8(可能也是 6 和 7,但未经测试),并且不会丢失您的价值或属性:
$.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();
$('#element').togglePassword($checkbox.prop('checked'));
试试这个
演示就在这里
$(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+'">');
});
这样可以更容易地工作:
document.querySelector('input[type=password]').setAttribute('type', 'text');
为了再次将其转回密码字段,(假设密码字段是第二个具有文本类型的输入标签):
document.querySelectorAll('input[type=text]')[1].setAttribute('type', 'password')
这是一种使用密码字段旁边的图像在看到密码(文本输入)和看不到密码(密码输入)之间切换的方法。我使用“睁眼”和“闭眼”的图像,但你可以使用任何适合你的东西。它的工作方式是有两个输入/图像,单击图像后,该值将从可见输入复制到隐藏的输入,然后交换它们的可见性。与许多其他使用硬编码名称的答案不同,这个答案足够通用,可以在一个页面上多次使用它。如果 JavaScript 不可用,它也会正常降级。
这是其中两个在页面上的样子。在此示例中,通过单击其眼睛来显示 Password-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>
这对我有用。
$('#newpassword_field').attr("type", 'text');
这是所有 IE8 爱好者的另一种选择,它在较新的浏览器中完美运行。您可以只为文本着色以匹配输入的背景。如果您只有一个字段,当您单击/聚焦该字段时,这会将颜色更改为黑色。我不会在公共网站上使用它,因为它会“混淆”大多数人,但我在 ADMIN 部分使用它,其中只有一个人可以访问用户密码。
$('#MyPass').click(function() {
$(this).css('color', '#000000');
});
-或-
$('#MyPass').focus(function() {
$(this).css('color', '#000000');
});
当您离开该字段时,这也需要将文本更改回白色。简单,简单,简单。
$("#MyPass").blur(function() {
$(this).css('color', '#ffffff');
});
[ 另一种选择 ] 现在,如果您要检查多个字段,并且所有字段都具有与我使用它相同的 ID,请将“pass”类添加到要隐藏文本的字段中。将密码字段类型设置为“text”。这样,只会更改类为“pass”的字段。
<input type="text" class="pass" id="inp_2" value="snoogle"/>
$('[id^=inp_]').click(function() {
if ($(this).hasClass("pass")) {
$(this).css('color', '#000000');
}
// rest of code
});
这是第二部分。这会在您离开字段后将文本更改回白色。
$("[id^=inp_]").blur(function() {
if ($(this).hasClass("pass")) {
$(this).css('color', '#ffffff');
}
// rest of code
});
我只是做了以下操作来更改输入的类型:
$('#ID_of_element')[0].type = 'text';
它起作用了。
我需要这样做,因为我在ASP NET Core 3.1项目中使用了jQuery UI datepickers,并且它们在基于Chromium的浏览器上无法正常工作(请参阅:https://stackoverflow.com/a/61296225/7420301)。
这对我有用。
<div class="ui icon input">
<input type="password" id="password">
<i class="eye slash link outline icon"></i>
</div>
JS系列
$(".eye").click(function() {
if ($('#password')[0].type === 'text') {
$('#password')[0].type = 'password';
$('.eye').addClass('slash');
} else {
$('#password')[0].type = 'text';
$('.eye').removeClass('slash');
}
});
下一个:如何仅在表格内应用边框?
评论