开发者

Rewrite inline javascript into jQuery

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开发者_StackOverflow中文版
</p>


Like this:

$('#ID of CheckBox').change(function() {
    $('#passwordID').attr('type', this.checked ? 'text' : 'password');
});


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜