2011-09-25 77 views
-2

我已啓用多發文本框使用jQuery。但是我不知道如果單選按鈕沒有被選中,如何重新啓用它們。我必須對當前的代碼進行哪些修改?啓用和禁用文本框的jQuery

<script type="text/javascript"> 

$(document).ready(function() {  

    $(":radio[id^=check]").click(function() { 
     var textId = "#" + this.id.replace("check", "text"); 
     $(textId).removeAttr("disabled", "disabled").css('background-color', '#99FF66') 
    }); 

//alert("test"); 

}); 
</script> 
+0

我不確定有人知道你真的想要做什麼或問。考慮更詳細地描述你的場景。我猜想,有一段時間你會解釋你想要做什麼,有人會建議如何解決它。 –

+0

好的,所以目前我有多個單選按鈕,涉及多個文本框。文本框全部禁用,以開始。此代碼在單擊某個單選按鈕時啓用某個文本框。但是,一旦單擊單選按鈕,然後取消單選按鈕,什麼也沒有發生,它應該保持啓用狀態,當它應該禁用和恢復。所以,我的問題是。當單選按鈕未被選中時,如何禁用文本框?或者當選擇它,然後取消選擇它?那有意義嗎?對不起,我不清楚。 – Alex

回答

1

您可以使用單個處理程序做兩個 - 當單選按鈕沒有被選中時禁用,當它啓用時啓用。使用@ AlienWebGuy的觀察,您可以使用該屬性值的檢查測試,因爲這是可以做到:

$(":checkbox[id^=check]").click(function() { 
    $("#" + this.id.replace("check", "text")) 
     .prop("disabled", $(this).filter(':checked').length == 0); 
}); 

當這個CSS再加

<style> 
    input:disabled { 
     background-color: #99ff66; 
    } 
</style> 
+2

理想的情況下,他會設置的CSS'輸入:禁用{背景顏色:#99FF66;}'然後他可以消除像這樣的情況:'$(文本).prop( '殘疾人',$(本).filter( ':checked')。length == 0);' – AlienWebguy

+0

@AlienWebguy - 好主意,我會更新。 – tvanfosson

+0

這些工作,但如果您取消選中單選按鈕,它不會再次禁用它。是因爲我從一開始就禁用了文本框? @AlienWebGuy – Alex

2

更換$(textId).removeAttr("disabled", "disabled")通過$(textId).removeAttr("disabled")

,如果你閱讀文檔這是很明顯的,removeAttr並不需要兩個參數

0

你要處理的財產,而不是屬性:

$(textId).prop('disabled',true);$(textId).prop('disabled',false');

0

我能夠完成任務這樣做。在財政上,我在我的文本框和單選按鈕上有id。該單選按鈕id =「check1」textbox id =「text1」,單選按鈕id =「check2」textbox id =「text2」。然後在我的拒絕ID我有單選按鈕id =「checker1」和文本框id =「text1」等。

因此,基於哪一個選擇它將啓用它並將其變爲綠色,或禁用並將其變爲紅色。

這是代碼。

<script type="text/javascript"> 

$(document).ready(function() { 

    //Goes through each and if click adds css and removes disable 
    $(":radio[id^=check]").click(function() { 
     var textId = "#" + this.id.replace("check", "text"); 
     $(textId).removeAttr("disabled").css('background-color', '#99FF66').css('color', '#000') 
     }); 

    //Goes through each and if checked adds disabled and turns red 
    $(":radio[id^=checker]").click(function() { 
     var textId = "#" + this.id.replace("checker", "text"); 
     $(textId).attr("disabled", "disabled").css('background-color', '#FF0033').css('color', '#FFFFFF') 
    }); 

//alert("test"); 

}); 
</script>