jQuery更改输入类型

Jam*_*mes 33 jquery attributes

尝试将input类型属性更改passwordtext.

$('.form').find('input:password').attr({type:"text"});
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用?

Nic*_*ver 54

你不能用jQuery做这件事,它明确禁止它,因为IE不支持它(检查你的控制台你会看到一个错误.

您必须删除输入并创建一个新输入,如果这是您所追求的,例如:

$('.form').find('input:password').each(function() {
   $("<input type='text' />").attr({ name: this.name, value: this.value }).insertBefore(this);
}).remove();
Run Code Online (Sandbox Code Playgroud)

你可以在这里尝试一下

要清楚的限制,jQuery将不允许改变type一个<button><input>如此行为是跨浏览器一致的(因为IE好好尝试一下允许的话,他们决定它无处不在禁止).尝试时,您将在控制台中收到此错误:

错误:无法更改type属性

  • 该死的,可爱的IE (23认同)
  • 它是2016年,jQuery允许现在更改属性. (11认同)
  • @Nick,我太害怕编辑你的代码,但我觉得你有一个错字:`.inserBefore(this)` (3认同)

Alo*_*lon 53

我的解决方案

    $('#myinput').clone().attr('type','tel').insertAfter('#myinput').prev().remove();
Run Code Online (Sandbox Code Playgroud)

  • 很好的解决方案,虽然根据已接受的答案,如果你有原始输入附加的事件,也会有问题... (4认同)
  • 非常优雅和简单:) (3认同)

ven*_*668 15

prop改用attr

$('.form').find('input:password').prop({type:"text"});
Run Code Online (Sandbox Code Playgroud)


Jas*_*Cav 10

我知道我的游戏有点晚了,但我只能在IE9中做到这一点(似乎微软决定允许它?).但是,我必须使用直接的JavaScript.这只是带有下拉列表的表单示例,该下拉列表根据下拉列表中选择的内容更改字段类型.

function switchSearchFieldType(toPassword) {
    $('#SearchFieldText').val('');
    if (toPassword === true) {
        $('#SearchFieldText').get(0).setAttribute('type', 'password');
    } else {
        $('#SearchFieldText').get(0).setAttribute('type', 'text');
    }
}

$('#SelectedDropDownValue').change(function () {
    if ($("select option:selected").val() === 'password') {
        switchSearchFieldType(true);
    }
    else {
        switchSearchFieldType(false);
    }
}).change();
Run Code Online (Sandbox Code Playgroud)


pro*_*_24 7

这应该很容易.

$("selector").attr('type', 'hidden'); 
//Changing it to hidden
Run Code Online (Sandbox Code Playgroud)


Cal*_*lat 5

现在是2018年,jQuery现在支持此功能。以下将起作用:

$('.form').find('input:password').attr("type","text");
Run Code Online (Sandbox Code Playgroud)