Reputation: 31
Hi I'm trying to get the text of "description" to put it in a table (then eventually do the same with "prix") there are many "item" so I can't just use an ID for each of them. so far the alert for val is giving me a blank while i want "HP portatif"
<div class="item" id="hp">
<img class="imageItem" src=".\\produits\\portable1.jpg" />
<div class="description">HP portatif </div>
<div class="prix">350.95</div>
<div class="ajouter" >Ajouter</div>
</div>
$(".ajouter").click(function(){
var val = $(this).children('div').text();
alert(val);
$('<tr>').appendTo('#corpsTableau');
$('<td>'+val+'</td><td><input type=\"text\" style=\"float:right\" /></td><td></td>').appendTo('#corpsTableau');
$('</tr>').appendTo('#corpsTableau');
});
Upvotes: 0
Views: 49
Reputation: 3509
In your case, I think is better to use one instead of on https://jsfiddle.net/xx4dL68u/
In this way, you will add the "item" name to the cart just one time.
$(".ajouter").one('click',function(){
var description = $(this).siblings('.description').text();
var corpsItem='<tr><td>'+description+'</td><td><input type="text" style="float:right" /></td><td></td></tr>';
$('#corpsTableau').append(corpsItem);
});
Upvotes: 0
Reputation: 181
The problem appears to be with your selector for "val". Try this:
var val = $(this).siblings('.description').text();
$(this) refers to the element you clicked, div.ajouter. We then look at all of that specific element's siblings for a description class. We then grab the text from that element.
Upvotes: 0
Reputation: 8868
To get the correct text, you need to target the element which is outside the scope of the element on which click event is triggered.
There are no. ways you can do it.
Using jquery .siblings()
$(".ajouter").click(function(){
var val = $(this).siblings('div.description').text(); // gets the siblings of the referenced element which has class 'description'
alert(val);
});
http://jsfiddle.net/s8jvoq2n/1/
Using jquery .parent()
$(".ajouter").click(function(){
var val = $(this).parent().find('.description').text(); // gets the parent of the referenced element and then find the div which has class 'description'
alert(val);
});
http://jsfiddle.net/s8jvoq2n/2/
Using jquery .closest()
$(".ajouter").click(function(){
var val = $(this).closest('div.item').find('.description').text(); // gets the closest occurring element of the referenced element with class 'item' and then find the div which has class 'description'
alert(val);
});
http://jsfiddle.net/s8jvoq2n/3/
Upvotes: 2
Reputation: 1283
I number of ways:
$(this).siblings('.description').text()
fiddle http://jsfiddle.net/alsosun/n59d2toj/
Upvotes: 0
Reputation: 3042
Because you're targeting the children of the .ajouter class, of which there are none. you can just target it like:
var val = $(this).text();
or
var val = $('.ajouter').text();
Upvotes: 0