2013-08-12 103 views
0

請參閱本琴:jQuery的不能檢查複選框

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"); 
    }  
}); 

當我第一次鍵入tex tbox,複選框已設置。當我刪除文本(長度= 0)沒有選中。

但是在取消選中之後,它無法重新檢查checbox。

任何人都知道如何解決這個問題?

回答

2

使用.prop(),而不是.attr() - 讀prop vs attr

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

演示:Fiddle

+0

感謝,工程巨大。你知道爲什麼我的代碼不能按預期工作嗎? –

+0

@TomGullen,因爲當'password.length = 0'時刪除屬性 – billyonecan

+1

@TomGullen還讀取了http://api.jquery.com/prop/#entry-longdesc和http下的「Attributes vs. Properties」部分://forum.jquery.com/topic/please-explain-attr-vs-prop-change-in-1-6 –