Wednesday, September 3, 2008

How to: Change text of asp:checkbox using java script

Problem : Change text of asp:checkbox when it is checked or unchecked.

Description : Lets we have a asp:checkbox and we need to change the text of asp:checkbox to 'Yes' when it is checked and 'No' when it is unchecked.

Solution :

Lets the checkbox is-

<asp:checkbox id="chkApproved" runat="server">
</asp:checkbox>



We can use getElementsByTagName function from javascript to get asp:checkbox text.

<Script language="javascript" type="text/javascript">
function toggleCheckText(objThis)
{
if (objThis.checked)
objThis.parentNode.getElementsByTagName("label")[0].innerHTML = "Yes";
else
objThis.parentNode.getElementsByTagName("label")[0].innerHTML = "No";
}
</script>

and to call this javascript -

<asp:checkbox id="chkApproved" runat="server" cssclass="normal_txt" onclick="toggleCheckText(this);"></asp:checkbox>

Hope it helps.

1 comment:

Anonymous said...

Thank you very much. It works.