Toggle label element in javascript
Hello everybody I've recently asked this question and I've given up with the 'replace input idea'. Instead I've decided to try another approach..
I've made my password field background transparent and I placed <label>
element "behind" the password input, so that it appears to be part of the password field. Now I wrote a standard function for toggling element like this :
function togglePassword(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'none' ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
}
I trigger this function onforus and onblur from password field so that label disappears when the password field is focused but I have problems with onblur, because after I type password and hit TAB on the which takes me to login submit button then the <label>
element appears with password value again and its mixed with typed password.
function togglePassword(obj) {
var el = document.getElementById(obj);
var input_el = document.getElementById('password_field');
if(input_el.value.length > 0)
{
el.style.display = 'none';
}
else {
if ( el.style.display != 'none' ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
}
}
Unfortunately, this code doesn't work .. can someone point to me where did I made mistake? So this second code should check whether password field is emtpy or not, if its not empty then continue to toogl开发者_开发百科e if it is don't toggle just hide the password value. Help :D thank you
Try this it will work
function togglePassword(obj) {
var el = document.getElementById(obj);
var input_el = document.getElementById('password_field');
if((input_el.style.display == ‘none’) || ((input_el.style.display=='') && (input_el.offsetWidth==0))){
el.style.display = 'block';
} else {
el.style.display = ‘none’;
}
}
}
One day I'll get round to writing up the details of this technique, but a working implementation has been sitting in my tmp directory for the last six months: http://dorward.me.uk/tmp/label-work/example.html
I have not quite understand the requirement, but you should verify in your function if you are doing a blur on focu action and reacting on this.
Perhaps something like that :
<script type="text/javascript">
function togglePassword(alwaysVisible, labelId, pwdId){
var label=document.getElementById(labelId);
if (alwaysVisible){
label.style.display="";
} else {
var pwd=document.getElementById(pwdId);
label.style.display= (pwd.value.length==0)?"":"none";
}
}
</script>
....
<form>
<label for="pwd" id="labelPwd">Type your password : </label>
<input name="pwd" id="pwd" onfocus="togglePassword(true, 'labelPwd', 'pwd')" onblur="togglePassword(false , 'labelPwd', 'pwd')" type="password">
<input type="submit">
</form>
HI,
try to use a library like JQuery. they are really helpful in such simple tasks, and also can handle quite complex ones...
important point is: such a thing like hiding/showing is solved already hundred times. do not reinvent the wheel ;-)
精彩评论