[javascript] change html input type by JS?

How to do this through the tag itself change type from text to password

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

Is it possible to insert JS inside the input tag itself to change type='text' to type='password'?

This question is related to javascript html input

The answer is


This is not supported by some browsers (IE if I recall), but it works in the rest:

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

or

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

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


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')">

Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).

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.

I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84

To work in 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>

<!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>

Try:

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

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

I had to add a '.value' to the end of Evert's code to get it working.

Also I combined it with a browser check so that input type="number" field is changed to type="text" in Chrome since 'formnovalidate' doesn't seem to work right now.

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

Here is what I have for mine.

Essentially you are utilizing the onfocus and onblur commands in the tag to trigger the appropriate 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:

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?