Jacksilky Jacksilky - 4 months ago 8
jQuery Question

Accessing a <p> tags value in JQuery

My aim is to have a button that once clicked, adds the contents of a certain
"p" tag (in-relation to the button) inside a list. The code I have so far is;

HTML:

<a href="GardenFurniture.html">
<div class="product">
<figure class="col-sm-3" height="220" id="product" >
<p class="PTitle"> <strong>Stylish Table and Chairs Set</strong></p>
<img src="GardenFurnitureImages/small.jpg"/>
</a>
<p style="display: inline" class="price"> Price: £499 </p>
<input style="display: inline" type='button' value='Add to Basket' class='addBasket'>
</figure>
</div>


Javascript:

$('.addBasket').click(function() {
var basketProduct = $(this).parent('.PTitle').val();
$('<li>').text(basketProduct).appendTo('.BasketBar');
});


I am trying to append the contents of
Ptitle
(Stylish Table and Chairs Set) into the list
BasketBar


This code just adds a blank space into the list any ideas on how to get my desired output?

Answer

First of all your html structure is invalid, the starting and ending of tags are not proper:

<a> tag and <figure> tag are not closing properly, so have a look into it and correct html first

I am posting answer by changing some html:

$('.addBasket').click(function(){
  // here we have used .siblings as we need to get text of same level element
  var basketProduct = $(this).siblings('.PTitle').text(); // use .text() for getting text inside any element
  alert(basketProduct)
  $('<li>').text(basketProduct).appendTo('.BasketBar');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="product">
  <figure class="col-sm-3" height="220" id="product" >
    <p class="PTitle"> <strong>Stylish Table and Chairs Set</strong></p>
    <img src="GardenFurnitureImages/small.jpg"/>
    <p style="display: inline" class="price"> Price: £499 </p>
    <input style="display: inline" type='button' value='Add to Basket' class='addBasket'>
  </figure>
</div>