2014-02-07 43 views
7

所以我試圖禁用一個文本字段,如果複選框沒有被選中,但它不能正常工作。jQuery的:檢查不工作?

例子:

<input type="checkbox" id="check" checked /><br /> 
#<input type="text" size="8" maxlength="6" id="colour" placeholder="ffffff" /> 

<script> 
    $('#check').change(function(){ 
     if($('#check:checked')){ 
      $('#colour').removeAttr('disabled'); 
     } else { 
      $('#colour').attr('disabled',''); 
     } 
    }); 
</script> 

這是什麼,我試圖做一個簡單的例子,但它不想工作。控制檯中沒有錯誤。

有人能解釋爲什麼這不起作用嗎?

回答

6

使用.prop()也使用的選中狀態設定值

$('#check').change(function() { 
    $('#colour').prop('disabled', !this.checked); 
}); 

演示:Fiddle

+0

感謝。出於某種原因,這是唯一在我的實際代碼中工作,即使所有其他人在jsfiddle中工作。謝謝你。 – Spedwards

1

使用length查找元素是否被檢查,否則您的條件將始終爲true。當長度大於0時,條件將是truefalse否則。

if($('#check:checked').length){ 
     $('#colour').removeAttr('disabled'); 
    } else { 
     $('#colour').attr('disabled',''); 
    } 

您可以直接使用checked屬性,而不必使用condtion。

$('#check').change(function() { 
    $('#colour').prop('disabled', !this.checked); 
}); 
1

試試這個:

$('#check').change(function(){ 
    if($('#check').is(':checked')){ 
     $('#colour').removeAttr('disabled'); 
    } else { 
     $('#colour').attr('disabled',''); 
    } 
}).change(); 

爲了使您的jsfiddle工作,你需要:

1)包括jQuery庫

2)使用is(':checked')檢查複選框是否被選中與否。

3)在頁面加載時觸發change()事件以捕獲默認的檢查狀態。

Fiddle Demo

1

使用this.checked

$('#check').change(function(){ 
    if(this.checked){ 
      $('#colour').removeAttr('disabled'); 
     } else { 
      $('#colour').attr('disabled',true); 
     } 
}); 

FIDDLE

1

在這裏你去:

http://jsfiddle.net/4dwkG/

<input type="checkbox" id="check" checked /><br /> 
#<input type="text" size="8" maxlength="6" id="colour" placeholder="ffffff" /> 

<script> 
    $('#check').change(function(){ 
     if($('#check').is(":checked")){ 
      $('#colour').removeAttr('disabled'); 
     } else { 
      $('#colour').attr('disabled',''); 
     } 
    }); 
</script> 
0

檢查這個code..using this.checked

$('#check').change(function(){ 

       if(this.checked) 
       $('#colour').removeAttr('disabled'); 
       else 
       $('#colour').attr('disabled','disabled'); 

     });