2016-08-24 88 views
0

我需要一些幫助,因爲我卡住了。Bootstrap/Javascript - 如果選中了一個複選框,否則全部取消選擇

所以基本上我有這樣的:

$(function() { 
$('.turn_on').on("click", function() { 
var checked = $(this).is(':checked'); 
var $otherChecks = $('.check_1, .check_2'); 
$otherChecks.removeAttr('disabled', checked); 
}); 
}); 

$('.turn_on').change(function() { 
if(this.checked){ 
var $otherChecks = $('.check_1, .check_2'); 
$otherChecks.removeAttr('disabled', checked); 
}else{ 
var checked = $(this).is(':checked'); 
var $otherChecks1 = $('.check_1, .check_2'); 
$otherChecks1.removeAttr('disabled', checked); 
} 
}); 

<form method="post"> 
<label class="checkbox"><input type="checkbox" name="turn_on" value="turn_on" class="turn_on">Turn on</label> 
<br> 
<label class="checkbox"><input type="checkbox" name="check_1" value="check_1" class="check_1" disabled>Option 1</label> 
<label class="checkbox"><input type="checkbox" name="check_2" value="check_2" class="check_2" disabled>Option 2</label> 
<button type="submit" class="btn btn-primary" name="submit">Save</button> 
</form> 

第一個腳本工作正常,但與「變」的劇本不起作用。 基本上,當用戶選中「turn_on」框時,它會「禁用」所有其他複選框。

我也擁有所有的div和腳本。 這只是代碼不能改變。

+0

php部分在哪裏? – Epodax

+0

什麼是PHP的一部分? @Epodax –

+0

您用php標記了您的問題 – Epodax

回答

0

怎麼樣:

$('.turn_on').on('change', function(){ 
     if($(this).prop("checked")){ 
     var $otherChecks = $('.check_1, .check_2'); 
     $otherChecks.removeAttr('disabled', checked); 
     }else{ 
     var checked = $(this).is(':checked'); 
     var $otherChecks1 = $('.check_1, .check_2'); 
     $otherChecks1.removeAttr('disabled', checked); 
    } 
    }); 

如果你說的代碼工作,但變化的功能不?嘗試上面的代碼,並評論是否仍然存在問題?

你缺少的$()在你的 「本」

編輯 - 新的答案。 當啓用/禁用時,你應該真的使用prop()insted - 我已經爲你創建了一個小提琴,它檢查和取消選中。

$(function() { 
$('.turn_on').on('change', function(){ 
    if($(this).prop("checked")){ 
    var $otherChecks = $('.check_1, .check_2'); 
    $otherChecks.prop('disabled', false); 
    }else{ 
    console.log('unchecked'); 
    var checked = $(this).is(':checked'); 
    var $otherChecks1 = $('.check_1, .check_2'); 
    $otherChecks1.prop("disabled", true); 
} 
}); 
}); 

如果我誤解你,而你仍然希望它總是刪除禁用,則只需將它設置爲true,而不是假的。 另外,如果你想刪除複選標記,只需prop(「check」,false); 小提琴測試是在這裏:https://jsfiddle.net/embtpspL/1/

+0

不,它不起作用。 :/ –

+0

@PatrykCz。我不認爲你問過這個問題吧? 我爲你創建了一個小提琴,它禁用和啓用。 如果這是你想要的,那麼在這裏留言,這樣我就可以改變我的答案。 - 小提琴 - > https://jsfiddle.net/embtpspL/1/ – Stender

相關問題