2017-12-27 816 views
0

我不明白爲什麼這段代碼不起作用。請嘗試在你的口水中具體,因爲它一定是非常愚蠢的東西。爲什麼我的禁用/啓用複選框在JQuery中不起作用?

$("#cagree").on("change", function(e){ 
 
\t \t if($("#chbx").attr("checked")){ 
 
\t \t  $("#submitbtn").button("enable"); 
 
\t \t } else { 
 
\t \t  $("#submitbtn").button("disable"); 
 
\t \t } 
 
\t \t 
 
\t \t });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title>My Page</title> 
 
\t <meta name="viewport" content="width=device-width, initial-scale=1"> 
 

 
</head> 
 
<body> 
 
<div data-role="page"> 
 

 
\t <div data-role="content"> \t 
 
\t \t <label><input type="checkbox" name="checkbox-0" id="chbx" class="cagree"> I agree </input></label> 
 
     <input type="button" value="Submit" id="submitbtn" class="submit" disabled/> 
 
\t </div><!-- /content --> 
 

 
</div><!-- /page --> 
 

 
</body> 
 
</html>

+2

可能重複[設置「選中」與jQuery複選框?](https://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery) –

+0

什麼是$( 「#submitbtn」)。button(「enable」)'應該這樣做?也沒有像''這樣的標籤 – j08691

回答

1

1. $("#cagree")必須$(".cagree")

2.使用.is(":checked")檢查複選框被選中或不

$("#submitbtn").button("enable") 3.Instead做$("#submitbtn").prop('disabled', false);和副通用

工作片段: -

$(".cagree").on("change", function(e){ // it's class so use . 
 
    if($(this).is(":checked")){ // use $(this) for current-object 
 
    $("#submitbtn").prop('disabled', false); // it's property so use .prop 
 
    }else{ 
 
    $("#submitbtn").prop('disabled', true); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <title>My Page</title> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 

 
    </head> 
 
    <body> 
 
    <div data-role="page"> 
 

 
     <div data-role="content"> \t 
 
     <label><input type="checkbox" name="checkbox-0" id="chbx" class="cagree"> I agree </label> 
 
     <input type="button" value="Submit" id="submitbtn" class="submit" disabled/> 
 
     </div><!-- /content --> 
 

 
    </div><!-- /page --> 
 

 
    </body> 
 
</html>

注: -

enabledisable的屬性,以便使用.prop()對其進行設置。

</input>是無效的,所以刪除。