When a user clicks Show link, display the password, hide it when clicked again

Daniel Harris picture Daniel Harris · Feb 23, 2012 · Viewed 55.3k times · Source

I am trying to get this simple script to work. Basically, when a user clicks on the Show link, it will display the password in the password text box and hide it when it is clicked again. I have searched for solutions but couldn't find anything for what I need. Here is the code:

JavaScript

    function toggle_password(target){
    var tag = getElementById(target);
    var tag2 = getElementById("showhide");
    if (tag2.innerHTML == 'Show'){
        tag.setAttribute('type', 'text');   
        tag2.innerHTML = 'Hide';
    }
    else{
        tag.setAttribute('type', 'password');   
        tag2.innerHTML = 'Show';
    }

    }

HTML

<label for="pwd0">Password:</label>
<input type="password" value="####" name="password" id="pwd0" />
<a href="#" onclick="toggle_password('pwd0');" id="showhide">Show</a>

When I click the link, nothing happens. I have tested this without using the if statement too and still did nothing.

Answer

ckozl picture ckozl · Feb 23, 2012

you weren't using document on for getElementById

function toggle_password(target){
    var d = document;
    var tag = d.getElementById(target);
    var tag2 = d.getElementById("showhide");

    if (tag2.innerHTML == 'Show'){
        tag.setAttribute('type', 'text');   
        tag2.innerHTML = 'Hide';

    } else {
        tag.setAttribute('type', 'password');   
        tag2.innerHTML = 'Show';
    }
}

your id names are illegal and difficult to work with: pwd'.$x.' you can't have some of those chars.

The HTML 4.01 spec states that ID tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.).

also, this method will not work in all browsers, in IE < 9 for instance you can only change .type before the element is attached to the document

try swapping them:

function swapInput(tag, type) {
  var el = document.createElement('input');
  el.id = tag.id;
  el.type = type;
  el.name = tag.name;
  el.value = tag.value; 
  tag.parentNode.insertBefore(el, tag);
  tag.parentNode.removeChild(tag);
}

function toggle_password(target){
    var d = document;
    var tag = d.getElementById(target);
    var tag2 = d.getElementById("showhide");

    if (tag2.innerHTML == 'Show'){

        swapInput(tag, 'text');
        tag2.innerHTML = 'Hide';

    } else {
        swapInput(tag, 'password');   
        tag2.innerHTML = 'Show';
    }
}

hope this helps -ck