Sunday, May 13, 2012

Change checkbox text using checkbox id in JavaScript

Lets first check how a check box is getting rendered in page. Lets have the following HTML-
<asp:CheckBox ID="chkAll" runat="server" Text="All" />
The above control is getting rendered like-
<input id="ContentPlaceHolder1_chkAll" type="checkbox" name="ctl00$ContentPlaceHolder1$chkAll" />
<label for="ContentPlaceHolder1_chkAll">All</label>
Now to change the text for the check box is nothing but changing the innerHTML of the rendered label. We can do this change by-
<script type="text/javascript">
    function changeLabel(checkboxID, text) {
        var allLabel = document.getElementsByTagName("label");
        for (i = 0; i < allLabel.length; i++) {
            if (allLabel[i].htmlFor == checkboxID) {
                allLabel[i].innerHTML = text;
    changeLabel('<%=chkAll.ClientID %>', "new text");
Using jQuery it much more simple-
$("label[for=<%=chkAll.ClientID %>]").html(new text);

No comments:

Post a Comment