0

Possible Duplicate:
How do I select text nodes with jQuery?

I am trying to move the data that is in the text node adjacent to a checkbox on the selection of the checkbox. I am using jquery. The methods I have tried are listed below with the results I received.

<input class="item" type="checkbox" /> Category 1
<input class="item" type="checkbox" /> Category 2


<script>
  $('.item').click(function(){
      if($(this).attr('checked'))
      {
         $('#list').append("<span>" + $(this).next() + "<span><br/>")
         //$(this).next() just writes "[object Object]"
         //$(this).next().text() doesn't write anything
         //Also tried $(this).nextSibling.nodeValue but throws "Cannot access property of undefined"
      }
      else
      {
          //This is remove the item from the list on uncheck 
      }
  });
</script>
Community
  • 1
  • 1
ExceptionLimeCat
  • 6,191
  • 6
  • 44
  • 77
  • Might be easier if you put this in a fiddle so we could see what elements you're using. But the `[object Object]` implies that you're getting the DOM element but not its contents. Did you try `$(this).next().val()`? – Marc Apr 22 '12 at 18:37
  • This question covers exactly the same ground as earlier questions on this topic; its answers may be merged with another identical question. http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery – iambriansreed Apr 22 '12 at 18:37
  • $(this).next().val() is writing "undefined" in my list. I don't really want to use that other example because I'm literally just trying to access the very next node. I'll try and put it in a fiddle but the list of checkbox items is being generated by another js file. I was trying to dumb it down to focus on this actual issue. – ExceptionLimeCat Apr 22 '12 at 19:04

1 Answers1

0

Consider having this markup instead

<input class="item" type="checkbox" id="cat_one" name="cat_one" /> <label for="cat_one">Category 1</label>
<input class="item" type="checkbox" id="cat_two" name="cat_two"/> <label for="cat_two">Category 2</label>

or this:

<label for="cat_one"><input class="item" type="checkbox" id="cat_one" name="cat_one" /> Category 1</label>
<label for="cat_two"><input class="item" type="checkbox" id="cat_two" name="cat_two"/> Category 2</label>

Thus you kill two birds with one stone: a) your markup is far semantically better and b) you can access the label elements content via the .text() method.

The first variant can be seen here: http://jsfiddle.net/skip405/DjWcg/

skip405
  • 6,119
  • 2
  • 25
  • 28
  • Actually I got it to work by setting the event to an anchor that is at a higher level in the node tree and accessing it's text node. But I think this method would work had I not gone that route. Thanks. – ExceptionLimeCat Apr 23 '12 at 20:10