Jesuraja
Jesuraja

Reputation: 3844

Get the Text from asp:CheckBox

I want to get the text of the asp:CheckBox using JavaScript.

<asp:CheckBox ID="chkRoles" runat="server" Text="Testing" onclick="javascript:test(this);" />

How to retrieve the text Testing from the checkbox? I have tried the following,

JavaScript

function test(obj)
{
    var text = obj.value;
}

Upvotes: 3

Views: 3147

Answers (3)

Tharif
Tharif

Reputation: 13971

You can use checkbox.nextSibling.innerHTML in javascript as shown below :

<script type="text/javascript">
        function changeCheckboxText(checkbox) {

            if (checkbox.checked) {
                alert(checkbox.nextSibling.innerHTML);
            }
        }
    </script>

The nextSibling property returns the node immediately following the specified node, in the same tree level.

Code :

CheckBox chk = new CheckBox();
chk.ID = "chkRoles";
chk.Text = "Check";
PlaceHolder1.Controls.Add(chk);
chk.Attributes.Add("onclick", "changeCheckboxText(this)");

Also using jQuery :

$("input:checkbox").click(function() {
  var $label = $(this).next('label');
  alert($label.text());
});

Reference

Upvotes: 3

Rojalin Sahoo
Rojalin Sahoo

Reputation: 1025

May this code will help you out:

<script type = "text/javascript">
    function GetSelectedItem()
    {
    var text;
       var CHK = document.getElementById("<%=chkRoles.ClientID%>");
       var checkbox = CHK.getElementsByTagName("input");
       var label = CHK.getElementsByTagName("label");
       for (var i=0;i<checkbox.length;i++)
       {
           if (checkbox[i].checked)
           {
               text = label[i].innerHTML;
               alert("Selected = " + label[i].innerHTML);
           }
       }
       return false;
    }
    </script>

Upvotes: 0

kalkanbatuhan
kalkanbatuhan

Reputation: 178

If you add ClientIDMode="Static" your Id doesn't change on client side.

 <asp:CheckBox ID="chkRoles" runat="server" Text="Testing" ClientIDMode="Static" onclick="javascript:test(this);" />

and you can do it with jquery like this

 function test(obj) {
        alert($(obj).next("label").html());
      }

Upvotes: 0

Related Questions