简体   繁体   English

通过 JavaScript 更改 HTML 表单“输入”类型

[英]Change HTML form 'input' type by JavaScript

How can I do this through the tag itself?我怎样才能通过标签本身做到这一点?

Change type from text to password将类型从文本更改为密码

<input type='text' name='pass' />

Is it possible to insert JavaScript code inside the input tag itself to change type='text' to type='password'?是否可以在输入标签本身内插入 JavaScript 代码以将 type='text' 更改为 type='password'?

Try:尝试:

<input id="hybrid" type="text" name="password" />

<script type="text/javascript">
    document.getElementById('hybrid').type = 'password';
</script>

Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).更改 <input type <input type=password>的类型会在某些浏览器(旧 IE 和 Firefox 版本)中引发安全错误。

You'll need to create a new input element, set its type to the one you want, and clone all other properties from the existing one.您需要创建一个新的input元素,将其type设置为您想要的类型,然后从现有的元素中克隆所有其他属性。

I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84我在我的 jQuery 占位符插件中执行此操作: https ://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84

To work in Internet Explorer:在 Internet Explorer 中工作:

  • dynamically create a new element动态创建新元素
  • copy the properties of the old element into the new element将旧元素的属性复制到新元素中
  • set the type of the new element to the new type将新元素的类型设置为新类型
  • replace the old element with the new element用新元素替换旧元素

The function below accomplishes the above tasks for you:下面的函数为您完成上述任务:

<script>
function changeInputType(oldObject, oType) {
    var newObject = document.createElement('input');
    newObject.type = oType;
    if(oldObject.size) newObject.size = oldObject.size;
    if(oldObject.value) newObject.value = oldObject.value;
    if(oldObject.name) newObject.name = oldObject.name;
    if(oldObject.id) newObject.id = oldObject.id;
    if(oldObject.className) newObject.className = oldObject.className;
    oldObject.parentNode.replaceChild(newObject,oldObject);
    return newObject;
}
</script>

Yes, you can even change it by triggering an event是的,你甚至可以通过触发一个事件来改变它

<input type='text' name='pass'  onclick="(this.type='password')" />


<input type="text" placeholder="date" onfocusin="(this.type='date')" onfocusout="(this.type='text')">

Here is what I have for mine.这是我的。

Essentially you are utilizing the onfocus and onblur commands in the <input> tag to trigger the appropriate JavaScript code.本质上,您正在利用 <input> 标记中的onfocusonblur命令来触发适当的 JavaScript 代码。 It could be as simple as:它可能很简单:

<span><input name="login_text_password" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="this.select(); this.setAttribute('type','text');" /></span>

An evolved version of this basic functionality checks for and empty string and returns the password input back to the original "Password" in the event of a null textbox:此基本功能的演进版本检查空字符串,并在出现空文本框时将密码输入返回到原始“密码”:

<script type="text/javascript">
    function password_set_attribute() {
        if (document.getElementsByName("login_text_password")[0].value.replace(/\s+/g, ' ') == "" ||
            document.getElementsByName[0].value == null) {

            document.getElementsByName("login_text_password")[0].setAttribute('type','text')
            document.getElementsByName("login_text_password")[0].value = 'Password';
        }
        else {
            document.getElementsByName("login_text_password")[0].setAttribute('type','password')
        }
    }
</script>

Where HTML looks like: HTML 看起来像这样:

<span><input name="login_text_password" class="roundCorners" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="password_set_attribute();" /></span>

I had to add a '.value' to the end of Evert's code to get it working.我必须在Evert 代码的末尾添加一个“.value”才能使其正常工作。

Also I combined it with a browser check so that the input type="number" field is changed to type="text" in Chrome since 'formnovalidate' doesn't seem to work right now.我还将它与浏览器检查相结合,以便在 Chrome 中将输入type="number"字段更改为type="text" ,因为 'formnovalidate' 现在似乎不起作用。

if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
    document.getElementById("input_id").attributes["type"].value = "text";

 let btn = document.querySelector('#btn'); let input = document.querySelector('#username'); btn.addEventListener('click',()=> { if ( input.type === "password") { input.type = "text" } else { input.type = "password" } })
 <input type="password" id="username" > <button id="btn">change Attr</button>

This is a simple toggle with jQuery .这是一个简单的jQuery切换。 It works also with the the ASP.NET MVC EditorFor() when you have a DataType.Password on the model property.当模型属性上有 DataType.Password 时,它也适用于ASP.NET MVC EditorFor()。

    function showPassword() {
        let password = $(".password");

        if (password[0].type == "password") {
            password[0].type = "";
        }
        else {
            password[0].type = "password";
        }
    }

 $(".show-pass").click(function (e) { e.preventDefault(); var type = $("#signupform-password").attr('type'); switch (type) { case 'password': { $("#signupform-password").attr('type', 'text'); return; } case 'text': { $("#signupform-password").attr('type', 'password'); return; } } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="password" class="show-pass">

This is not supported by some browsers (Internet Explorer if I recall), but it works in the rest:某些浏览器不支持此功能(如果我记得是 Internet Explorer),但它在其余浏览器中有效:

document.getElementById("password-field").attributes["type"] = "password";

or或者

document.getElementById("password-field").attributes["type"] = "text";
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" language="javascript">
function changefield(){
    document.getElementById("passwordbox").innerHTML = "<input id=\"passwordfield\" type=\"password\" name=\"password-field\" title=\"Password\" tabindex=\"2\" />";
    document.getElementById("password-field".focus();
}
</script>
</head>

<body>
<div id="passwordbox">
<input id="password-field" type="text" name="password-field" title="Password"onfocus="changefield();" value="Password" tabindex="2" />
</div>
<input type="submit" name="submit" value="sign in" tabindex="3" />

</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM