开发者

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=''};"开发者_如何学Python />
<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");


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 + '" />');
}


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

Hope it helps someone

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜