[英]How do i disable a submit button when checkbox is uncheck?
我這里有些東西似乎無法幫助我禁用提交按鈕。 有任何想法嗎?
<input type="checkbox" checked="checked" id="checky"><a href="#">terms and conditions</a>
<input type="submit" id="postme" value="submit">
$('#checky').click(function(){
if($(this).checked == false){
$('#postme').attr("disabled","disabled");
} else {
$('#postme').removeAttr('disabled');
}
});
你應該檢查屬性checked
,而不是方法。
更新小提琴: http : //jsfiddle.net/8YBu5/7/
$('#checky').click(function(){
if($(this).attr('checked') == false){
$('#postme').attr("disabled","disabled");
} else {
$('#postme').removeAttr('disabled');
}
});
編輯
請記住,這段代碼需要包含在$(document).ready()
或者放在html代碼的底部,否則你的JS會將自己綁定到尚未加載的DOM元素並且會失敗。
將它包裝在.ready()中
<script type='text/javascript'>
$(document).ready(function(){
$('#checky').click(function(){
if($(this).attr('checked') == false){
$('#postme').attr("disabled","disabled");
} else {
$('#postme').removeAttr('disabled');
}
});
});
</script>
此代碼可以放在文檔中的任何位置,只有在DOM准備好后才會觸發,因此您不必擔心過早的觸發器。
將它放在文檔的底部
<!-- some HTML -->
<script type='text/javascript'>
$('#checky').click(function(){
if($(this).attr('checked') == false){
$('#postme').attr("disabled","disabled");
} else {
$('#postme').removeAttr('disabled');
}
});
</script>
</body>
</html>
如果你把它放在文檔的底部,你不需要將它包裝在.ready()
因為在加載其他所有內容之前不會讀取javascript。 這種方法有一個性能提升(如果你有很多JS)
您可以使用這些方法中的任何一種來確保JS僅在完成加載后才將事件處理方法綁定到DOM元素。
在jQuery 1.6 attr
之前,在1.6之后你必須使用prop
。
$('#checky').click(function(){
$('#postme').prop('checked', !$(this).checked);
})
屬性和屬性是不同的東西,但不幸的是jQuery花了很長時間來區分它們。
另請參見: .prop()vs .attr()
if(!$(this).is(':checked') ...
將$(this).checked
為if($(this).attr('checked') == false){
在這里你去。
試試這個
$(document).ready(function(){
$("#postme").attr("disabled","disabled");
$("#checky").click(function(){
if($("#checky").is(":checked")){
$("#postme").removeAttr("disabled");
}
else{
$("#postme").attr("disabled","disabled");
}
});
})
試試這種方式
$('#checky').click(function(){
if(this.checked == false){
$('#postme').attr("disabled","disabled");
}
else {
$('#postme').removeAttr('disabled');
}
});
添加按鈕#postme
一個單擊事件,檢查是否選中了復選框。 如果選中,則返回false,否則返回true。
$('#postme').click( function () {
if ( !$('#checky').attr('checked') ) {
return false;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.