61

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'?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1150271
  • 685
  • 2
  • 7
  • 8

13 Answers13

58

Try:

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

<script type="text/javascript">
    document.getElementById('hybrid').type = 'password';
</script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
deed02392
  • 4,799
  • 2
  • 31
  • 48
12

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')">
Srinath
  • 275
  • 3
  • 11
12

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>
Ky -
  • 30,724
  • 51
  • 192
  • 308
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
  • Would this work without using all the if conditions? I am having the same issue, but I don't need the objects to equal each other. – JP Hochbaum May 20 '16 at 20:06
  • 1
    @JPHochbaum Sure. In fact, my original answer didn’t contain all that extra code — someone else added it. – Mathias Bynens May 22 '16 at 14:44
3

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. 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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lou Grossi
  • 2,289
  • 2
  • 14
  • 8
1

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 the 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";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

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>
NimaDoustdar
  • 318
  • 3
  • 5
  • 1
    An explanation would be in order. E.g., what is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/70255395/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Jun 08 '22 at 10:43
1

This is a simple toggle with jQuery. It works also with the the ASP.NET MVC EditorFor() when you have a DataType.Password on the model property.

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

        if (password[0].type == "password") {
            password[0].type = "";
        }
        else {
            password[0].type = "password";
        }
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rainhider
  • 806
  • 1
  • 17
  • 31
0

$(".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">
  • 1
    This doesn't show how to change a type using vanilla Javscript, it's a jQuery approach. That's becoming less and less relevant since jQuery isn't used much for new projects. – moopet Jun 03 '20 at 14:21
0

You can try this:

const myTimeout = setTimeout(show, 5000);

function show() {
  document.getElementById('pass').type = "text";
}

clearTimeout(myTimeout);
Aaron Meese
  • 1,670
  • 3
  • 22
  • 32
0
 //html
 <input type="password" id="password_input">
 <i onclick="passwordDisplay()" class="ti-eye"></i>

 //js
 const input = document.getElementById("password_input")

 function passwordDisplay() { 
    if (input.attributes["type"].value == "text")
        input.attributes["type"].value = "password"
     else
        input.attributes["type"].value = "text"
    
 }
  • Please avoid code only answer, and add some explanation. Especially when answering to old questions, it is important to explain why your answer is different, and even better than existing answers. See [answers]. – chrslg Feb 10 '23 at 08:26
0

You can use the JavaScript setAttribute method elementName.setAttribute('class') = 'value';

Abdulfattah
  • 111
  • 2
  • 6
0

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

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

or

document.getElementById("password-field").attributes["type"] = "text";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Evert
  • 8,161
  • 1
  • 15
  • 17
-1
<!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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Karan Shah
  • 744
  • 5
  • 15
  • 1
    An explanation would be in order. Please respond by [editing (changing) your question/answer](https://stackoverflow.com/posts/9094107/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Jun 08 '22 at 10:32