views:

157

answers:

2

Using JQuery, is there a simple way to select the text immediately after a checkbox?

<li>bleh..</li>
<li>
    <input type="checkbox" id="cbx1" value="10" />&nbsp;Very important text.
</li>
<li>bleh..</li>

I want to use jquery to select that "Very important text." minus &nbsp;

+2  A: 

To do what you said:

var text = $('#cbx1').parent().text();

You might need to trim it though, not sure about the &nbsp;:

var text = $.trim($('#cbx1').parent().text());
Matt Huggins
+1, The trim version is the best complete answer for this.
Nick Craver
Ah so .text() will actually get the text and ignores the html elements (the checkbox)? Now I am clear the differences between .text() and .html()
Rosdi
+5  A: 

Better solution might be to wrap the text in a label element:

<li>
    <input type="checkbox" id="cbx1" value="10" />
    <label for="cbx1">Very important text.</label>
</li>

You can then get the text like so:

var text = $('label[for="cbx1"]').text();

This also improves the semantics of your document.

harto
Thanks.. I like the fact the checkbox is toggled when I click on the text, just the way we are accustomed to in Windows.
Rosdi