Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

html - Javascript change input type dynamically doesnt work on IE8

i have a input field for entering password in a webpage:

<input name="txtPassword" type="text" class="input2" id="txtPassword" value="Password" onfocus="txtOnFocus2('txtPassword','Password');" onblur="txtOnBlur2('txtPassword','Password');" />

in the initial state the usershould read "password" as the initial value and when he starts typing a password, the field should change to type password. Also when he sets it back to blank or initial value the field should change type to "text" and show password.

I wrote code an got it working on Firefox, Chrome, and safari and its not changing the type to password on IE 8.

this is the js code i made by editing an existing function code:

 function txtOnFocus2(elementId, defaultText)
 { 
    if (document.getElementById(elementId).value == defaultText)
    {
       document.getElementById(elementId).value = "";
  document.getElementById(elementId).type = "password";
    }
 }

 function txtOnBlur2(elementId, defaultText)
 {
    var textValue = document.getElementById(elementId).value;

    if (textValue == defaultText || textValue.length == 0)
    {
      document.getElementById(elementId).type = "text"; 
  document.getElementById(elementId).value = defaultText;
    }
 }

This is working fine in Firefox,chrome and safari but doesn't change field type on IE 8.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An alternative solution would be to change your approach altogether. The following technique degrades gracefully, is more accessible, and less JavaScript-dependant:

HTML

<div><label for="email">Email</label> <input type="text" name="email" id="email" /></div>
<div><label for="password">Password</label> <input type="password" name="password" id="password" /></div>

JavaScript

$('input')
    .focus(function() {
        $(this).css('background-color', 'white');
    })
    .blur(function() {
        if($.trim($(this).val()) == '') {
            $(this).css('background-color', 'transparent').val('');
        }
    });

CSS

input {
    background-color: transparent;
    padding: 2px;
}

label {
    color: gray;
    padding: 2px 4px;
    position: absolute;
    z-index: -1;
}

Live demo: http://jsfiddle.net/rjkf4/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...