Manoj Pandey
Manoj Pandey

Reputation: 4666

How to get the text associated with a checkbox

I am trying to access the text associated with a checkbox. What is the attribute of the chekcbox object that points to the text associated with that. Thus, in the following example, I would like to alert the user saying "Selected -- TextXYZ".

<form id="idForm" class="classForm">
<input type="checkbox" id="idCheckbox"> TextXYZ <br>
</form>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script type="text/javascript">
function clickCheckbox() {alert("Selected -- " + this.name);}
$(document).ready( function() {
    $("#idCheckbox").click(clickCheckbox);
});
</script>

Upvotes: 2

Views: 2157

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You can use the nextSibling dom property to get hold of the text node coming after the checkbox

Try

function clickCheckbox() {
    alert("Selected -- " + $.trim($(this.nextSibling).text()));
}
$(document).ready( function() {
    $("#idCheckbox").click(clickCheckbox);
});

Demo: Fiddle

Upvotes: 6

sergioadh
sergioadh

Reputation: 1471

Use a label for the text and use the for attribute.

Upvotes: 2

Related Questions