siva636
siva636

Reputation: 16441

Jquery selector for the label of a checked checkbox

We can select the checked checkbox (in jQuery) as follows:

jQuery(:checked)

But how can we select the label of the checked checkbox in jQuery?

Upvotes: 4

Views: 11461

Answers (3)

Samich
Samich

Reputation: 30095

Checkbox text is label element. Simply search it with mathces of for attribute:

In html it looks like:

<input type="checkbox" name="chk" />
<label for="chk">Checkbox 1</label>

You can find it like:

jQuery('input[type=checkbox]:checked').map(function() {
    return $('label[for=' + $(this).attr('name') + ']');
});

This will return all the checkboxes labels. Label is not required to be next or previous element near checkbox.

Upvotes: 3

sikrip
sikrip

Reputation: 681

Assuming you have this html

<label>Label</label>
<input type="checkbox" checked="checked"> test </input>
<label>Label 2</label>
<input type="checkbox" > test 2 </input>
<label>Label 3</label>
<input type="checkbox" > test 3</input>

you can find the label using

$("input:checked").prev('label');

*use .next if you have the label after the checkbox in your html

*use .parent if you wrapped the checkbox in the label element

Upvotes: 2

Royi Namir
Royi Namir

Reputation: 148524

checkbox doesnt come with text ( in asp.net it DOES)

jQuery(":checked").next('span').html() //next or prev ( depends n direction)

Upvotes: 5

Related Questions