Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the Text of an asp:CheckBox when clicked

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.

like image 273
sunpost Avatar asked Dec 14 '22 05:12

sunpost


2 Answers

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.

like image 123
Robert C. Barth Avatar answered Dec 15 '22 19:12

Robert C. Barth


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");
    }
});
like image 27
tanathos Avatar answered Dec 15 '22 20:12

tanathos