tim lieberman
tim lieberman

Reputation: 13

Jquery -- Accessing a childs value when clicking on the parent div

I've made a row striped table using divs instead of tables (I hate tables). I want to make it so that if I click on one of the divs I can grab one of its childs values.

  <div class='row'><!-- I want to click this div -->

         <p>I want this value</p>

         <p>some other val</p>            

  </div>

  <div class='row'>

         <p>I don't want this one</p>

         <p>some other val</p>            

  </div>

Let me know if you have a answer.

Upvotes: 1

Views: 90

Answers (6)

vdegenne
vdegenne

Reputation: 13270

$('.row p').bind('click', function(){
   this.value;
});

Upvotes: 0

Gabe
Gabe

Reputation: 50475

$('.row').click(function(){
   $('p', this).each(function(){
      alert($(this).text());
   });

});

Upvotes: 0

Jason Kaczmarsky
Jason Kaczmarsky

Reputation: 1686

$('.row').click(function(){
    console.log($(this).children('p').text());
});

Upvotes: 0

Brian Hoover
Brian Hoover

Reputation: 7991

If you can put classes into the p tags, this would be easy.

  <div class='row'><!-- I want to click this div -->
         <p class="selectable">I want this value</p>
         <p>some other val</p>            
  </div>
  <div class='row'>
         <p>I don't want this one</p>
         <p  class="selectable">some other val</p>            
  </div>
$('.row').click(function(){
  $(this).children(".selectable").function();
})

Upvotes: 0

gilly3
gilly3

Reputation: 91467

Something like this:

$(".row").click(function(){
    var grabbedValue = $("> p:eq(0)", this).text();
    // do something with grabbedValue;
});

Upvotes: 0

Stefan Kendall
Stefan Kendall

Reputation: 67802

$('.row').click(function(){
   var value = $(this).find('p').eq(0).text();
});

Of course, you'll probably want to mark your inner values a little better to fix the inner find() selector. Example:

<div class="row">
   <span class="row-value">35</span>
   <p>Some descriptive text</p>
</div>
<div class="row">
   <h1>Cool header</h1>
   <span class="row-value">5</span>
</div>

Then you could use $(this).find('.row-value').text() and feel better about the selector not breaking.

Upvotes: 3

Related Questions