Sideshow
Sideshow

Reputation: 1361

jQuery selecting text from within span

I have a dynamic list created and need to be able to select data held within two span tags when clicked. My code so far is:

var app_data="<li class='auto' 
    data-short='"+this['dish_short']+"' 
    data-desc='"+this['dish_desc']+"' 
    data-dish_id='"+this['dish_id']+"'>
         <span class='m_name'>"+this['dish_name']+"</span> - £<span 
         class='m_price'>"+this['dish_price']+"</span>
</li>";

Please note that the line breaks within the code are to make it more readable rather than it being all on one line.

What I am trying to do is select the text from each of the span classes although so far with the code below it is selecting all the text eg. the dish name AND the dish price.

Code:

 $('li').click(function(){
    //alert($('li', this).data('short'));
    var m_name=$(this, 'span .m_name').text();
    console.log(m_name);
    });

Upvotes: 0

Views: 676

Answers (2)

Dipesh Parmar
Dipesh Parmar

Reputation: 27382

For dynamic list created use .on to assing click or other events.

Example

$(document).on('click','li',function(){
   //code here
});

Upvotes: 3

VisioN
VisioN

Reputation: 145478

The context part goes as the second argument (i.e. $(selector, context)), as well as m_name class is set to <span> elements, so there shouldn't be any space in the selector:

var m_name = $("span.m_name", this).text();

Upvotes: 3

Related Questions