2013-07-30 55 views
0

在這個程序中,當複選框未被選中時,我需要禁用Html按鈕。僅當選中複選框時才應啓用按鈕。即時通訊使用Jquery版本1.8.3。然而,在這個程序之間交換啓用和禁用不能按我的預期工作。JQuery removeAttr和attr

// ------ HTML

<body> 
Some agreement here 
<p> 
    <input type="checkbox" id="agree" /> 
</p> 
<input type="button" value="Continue" disabled="disabled" id="continue"/> 

<script type="text/javascript" src="js/jquery-1.8.3.js"></script> 
<script type="text/javascript" src="js/class.js"></script> 
</body> 

// ------ JQuery的

$(document).ready(function(){ 
    $('#agree').change(function(){ 
     state = $(this).attr('value'); 
     if(state == 'on'){ 
      $('#continue').removeAttr('disabled'); 
     }else if(state == ''){ 
      $('#continue').attr('disabled','disabled'); 
     } 

    }); 
}); 
+0

你說「沒有工作,我期待」 - 是什麼問題到底是什麼? – SmokeyPHP

回答

1

嘗試以下函數:

$(document).ready(function(){ 
    $('#agree').change(function(){ 
     var checked = $(this).prop('checked') 
     if(checked){ 
      $('#continue').removeAttr('disabled'); 
     }else{ 
      $('#continue').attr('disabled','disabled'); 
     } 
    }); 
}); 

this fiddle.

總之,你檢查的價值#agree,其中沒有設置在任何點。 prop()是確定是否選中複選框的更好方法。 prop()將返回truefalse,使事情變得更容易。

+0

感謝您的解決方案。這是與版本1.8兼容的 – amal

+1

它是。如果您查看[the fiddle](http://jsfiddle.net/5SNrW/),您會在左側的邊欄中看到我使用的是jQuery 1.8.3版本。 – theftprevention

+0

是的。最後它起作用。 thnx – amal

2

對於disabled(和checked),你應該使用.prop()

$("#continue").prop("disabled",true); 

雖然它會幫助,如果你讓我們知道什麼是不按預期工作

0

禁用的屬性後面不需要="disabled"。只要這樣做:

<input type="button" value="Continue" disabled /> 

而你應該使用.prop('disabled', true)而不是反正。還有.removeProp()

1
$(document).ready(function(){ 
    $('#agree').change(function(){ 
     if($(this).is(":checked")){ 
      $('#continue').removeAttr('disabled'); 
     }else{ 
      $('#continue').attr('disabled','disabled'); 
     } 

    }); 
}); 
+0

非常感謝您的解決方案。這也是我的問題的正確解決方案。 – amal

0
$(document).ready(function(){ 
     $('#agree').click(function(){ 
      $("#continue").attr("disabled", !this.checked); 

     }); 
    }); 

我希望這會有所幫助。 看到Fiddle

0

一個簡單的方法是使用this.checked或使用$(this).is(":checked")prop一起操縱input:button

$('#agree').change(function() { 
    $("#continue").prop("disabled", !$(this).is(":checked")); 
    //$("#continue").prop("disabled", !this.checked); 
}); 

演示:http://jsfiddle.net/hungerpain/p9u7Y/