0

How do I rewrite this using jQuery instead of the onchange event?

<input name="PasswordName" type="password" id="passwordID">
<p>
<input type="checkbox" onchange="document.getElementById('passwordID').type = this.checked ? 'text' : 'password'"> Show Password
</p>
2
  • 1
    I believe this will not work correctly in IE. Commented May 17, 2010 at 16:35
  • 2
    Make sure to test this in IE, since it won't allow you to do this, at least not as you have it, you'll have to remove/add an input element, the type is immutable in IE :) Commented May 17, 2010 at 16:36

2 Answers 2

4

Like this:

$('#ID of CheckBox').change(function() {
    $('#passwordID').attr('type', this.checked ? 'text' : 'password');
});
Sign up to request clarification or add additional context in comments.

2 Comments

No need to get the underlying element - $('#passwordID').attr('type', ...)
As noted in the comments to the original question - this will NOT WORK in Internet Explorer since IE can't change the type attribute! bug: webbugtrack.blogspot.com/2007/09/…
3

If this is your exact markup, you can do this. Also note this is updated to actually work across different browsers. Since your checkbox does not currently have an id, I am using a sibling selector to access it through its parent p tag:

jQuery(function($){ // DOM Ready

  $("#passwordID + p input").click(function(){
     var new_type = $(this).is(':checked') ? "text" : "password",
         pwd      = $("#passwordID"); // We keep replacing it, so find it again
     if(pwd.attr('type') !== new_type){
       pwd.replaceWith( 
          $("<input />", {type: new_type, value: pwd.val(), id: "passwordID", name: "PasswordName"})
       );
     }
  }).click(); // Trigger it once on load in case browser has remembered the setting

});

Demo on JSBin

5 Comments

Zounds! I'm glad that I asked!
I tried this in IE8 on JSBin - it will show the value, but not hide it again.
What is !==? I know about == and !=, but !==?
id: "#passwordID" should be id: "passwordID"
@scunliffe and @cf_PhillipSenn, I updated the post to fix the ID problem. Sorry about that! @cf_PhillipSen !== is a strict not equals (no type conversion). === is strict equals. 0 != "0" => false whereas 0 !== "0" => true. Anywhere where you know for sure the types should match, you should use === or !==.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.