简体   繁体   中英

programatically change textbox type from type='text' to type='password'

i have username and password textboxes. i want them to both show the default text, ie "username" and "password", but when the user clicks on the password box it should dynamically change to a "password" type for security reasons.

i've managed to do this easily enough with javascript code but it doesn't want to work in IE.

<input id="username" class="username" name="u" type="text" value="username" onclick="if(this.value='username') {this.value=''};" />
<input id="password" class="password" name="p" type="text" value="password" onclick="if(this.value='password') {this.value=''; this.type='password'};" /> 

Let say your html code is like this

<input type="text" id="txtId" />

you can replace it by using Jquery,

$('#txtId').replaceWith('<input type="password" id="txtId" />')

IE only lets you set the type of an input element once, when the element is created. Attempts to set it after that will fail.

If you want to "change" the element in IE, what you'll likely need to do is create another element with the same attributes (except for the type, of course), and replace the existing element with it.

Or create a dummy textbox for the password, and have the real password box hidden -- on focus the dummy box should hide itself, and show and focus on the real password box.

Would you consider using JQuery?

$("[name=fieldname]").attr("type", "password");

This worked for me Put this in the head section

function changeBack()
 {
     if(document.getElementById('smsl_pw').value=='')
     {
        document.getElementById('smsl_pw').type='text';
        document.getElementById('smsl_pw').value='Password';

     }

 }

 function changePass()
 {
    document.getElementById('smsl_pw').type='password'; 
    document.getElementById('smsl_pw').value='';

 }

Here is the input field <input id="smsl_pw" onclick="changePass();" onblur="changeBack();" name="smsl_pw" type="text" value="Password"> <input id="smsl_pw" onclick="changePass();" onblur="changeBack();" name="smsl_pw" type="text" value="Password">

Hope it helps someone

Here is a function to replace any form element by a password with the same value, knowing its id:

function replaceWithPassword(id)
{
    var o = $('input#' + id + ', textarea#'+id + ', select#'+id);
    o.replaceWith('<input type="password" value="' + o.val() + '" id="' + id + '" />');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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