0

Refer to this fiddle:

http://jsfiddle.net/FwSF3/

HTML:

<input type="password" id="Password" tabindex="2">
<input id="PasswordChk" type="checkbox" disabled="disabled"/>

JS:

$('#Password').on("keyup", function () {
    var password = $.trim($(this).val());    
    if(password.length == 0){
        $('#PasswordChk').removeAttr("checked");
    }else{
        $('#PasswordChk').attr("checked", "checked");
    }    
});

When I first type into the textbox, the checkbox is set. When I remove the text (length = 0) it's unchecked.

However after unchecking, it can't re-check the checbox.

Anyone know how to get around this?

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456

1 Answers1

2

Use .prop() instead of .attr() - read prop vs attr

$('#Password').on("keyup", function () {
    var password = $.trim($(this).val());    
    $('#PasswordChk').prop("checked", password.length > 0);
});

Demo: Fiddle

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Thanks, works great. Do you know why my code doesn't work as expected though? – Tom Gullen Aug 12 '13 at 11:28
  • @TomGullen because you're removing the attribute when `password.length = 0` – billyonecan Aug 12 '13 at 11:29
  • 1
    @TomGullen also read the `Attributes vs. Properties` section under http://api.jquery.com/prop/#entry-longdesc and http://forum.jquery.com/topic/please-explain-attr-vs-prop-change-in-1-6 – Arun P Johny Aug 12 '13 at 11:32