簡體   English   中英

jQuery復選框,用於啟用/禁用文本輸入並添加/刪除默認值

[英]jQuery checkbox to enable/disable text input and add/remove default value

我正在嘗試創建一個小的可重用函數,當選中該函數時,將禁用文本字段並插入默認值“160”,如果未選中,則啟用該字段並刪除該值。 我已經完成了它,但是未檢查的部分讓我失望了。

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


   if ($('#chkIsTeamLead').checked = true){
      $('#txtNumHours').val('160').attr('disabled', 'disabled');
      console.log('checked');
   }

  if ($('#chkIsTeamLead').checked = false){
     $('#txtNumHours').val('').removeAttr('disabled');
     console.log('unchecked');
   }

});

我把它設置為一個可重用的函數,傳遞給它的參數,但這給了我更多的麻煩,我希望參數是復選框,目標和值,最好鏈接到我當前的代碼: http//codepen.io/AlexBezuska / pen / bwgsA感謝您提供的任何幫助!

工作jsFiddle演示

  1. 使用.is(':checked')
  2. 您必須將兩個值與==進行比較。
  3. 當您使用像disabled這樣的屬性時,最好使用.prop()方法而不是.attr()

$('#chkIsTeamLead').change(function(){
    if ($('#chkIsTeamLead').is(':checked') == true){
        $('#txtNumHours').val('160').prop('disabled', true);
        console.log('checked');
    } else {
        $('#txtNumHours').val('').prop('disabled', false);
        console.log('unchecked');
    }
});

參考文獻:

試試這個

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


   if ($('#chkIsTeamLead').is(':checked')){
      $('#txtNumHours').val('160').attr('disabled', 'disabled');
      console.log('checked');
   } else {
     $('#txtNumHours').val('');
    $('#txtNumHours').removeAttr('disabled');
     console.log('unchecked');
   }
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM