tags:

views:

57

answers:

2

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>
+4  A: 

Like this:

$('#ID of CheckBox').change(function() {
    $('#passwordID').attr('type', this.checked ? 'text' : 'password');
});
SLaks
No need to get the underlying element - $('#passwordID').attr('type', ...)
Keith Rousseau
Yes, you're right.
SLaks
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: http://webbugtrack.blogspot.com/2007/09/bug-237-type-is-readonly-attribute-in.html
scunliffe
+3  A: 

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

Doug Neiner
Zounds! I'm glad that I asked!
cf_PhillipSenn
+1 Thank you for the correction. I deleted my answer.
patrick dw
I tried this in IE8 on JSBin - it will show the value, but not hide it again.
scunliffe
What is !==? I know about == and !=, but !==?
cf_PhillipSenn
id: "#passwordID" should be id: "passwordID"
cf_PhillipSenn
@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 `!==`.
Doug Neiner