views:

2270

answers:

3

How can I change the Text for a CheckBox without a postback?

<asp:CheckBox ID="CheckBox1" runat="server" Text="Open" />

I would like to toggle the Text to read "Open" or "Closed" when the CheckBox is clicked on the client.

+1  A: 

3 Easy Options

Use JavaScript to change the text client side- By Registering the Event in the .CS class like so:

CheckBox1.Attributes.Add("JavaScipt")

Use an HTML Checkbox with JQuery

Or put in an an Ajax Update Panel

Some AJax starter Videos

cgreeno
The first option won't work. input[type=checkbox] don't have text attributes.
Robert C. Barth
My bad it does create a label with a "for" attribute that I thought was rendered into a change event on the checkbox to the label however I was mistaken
cgreeno
+1  A: 

If you're interested to use a framework javascript like jQuery, i propose a solution ilke this:

$("input[id$=CheckBox1]").click(function() {
    if ($(this).attr("checked")) { 
        $(this).next("label:first").text("Open");
    }
    else {
        $(this).next("label:first").text("Close");
    }
});
tanathos
+4  A: 
function changeCheckboxText(checkbox)
{
  if (checkbox.checked)
    checkbox.nextSibling.innerHTML = 'on text';
  else
    checkbox.nextSibling.innerHTML = 'off text';
}

called as:

<asp:CheckBox runat="server" ID="chkTest" onclick="changeCheckboxText(this);" />

Just FYI, it's usually bad practice to change the text of the checkbox label because it tends to confuse the user.

Robert C. Barth
This is probably the best bet. ASP.NET controls do not provide an easy way to get the `id` attribute, so you typically can't just use `$('#someid'). I try to avoid `onclick` attributes, but in this case this is the easiest way.
swilliams
It would have been OK to use <%=chkTest.ClientID%> with document.getElementById() (or $(#'<%=chkText.ClientID %>') if using JQuery), however, the label that the checkbox control emits doesn't have an ID, but you're pretty much guaranteed it will be right after the checkbox.
Robert C. Barth
Thanks. That works great.
sunpost