Reputation: 3844
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
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());
});
Upvotes: 3
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
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