Skip to content
Advertisement

Capture text inside a using JavaScript

I need to create a shopping cart. When I click the button “Add to Cart”, the item in the “p” should appear in the screen.

PHP

<?php foreach($product as $prods) { ?>
    <div class="prod">
          <p class="test"><?php echo $prods['name'] ?></p>
          <button type="submit" onclick="addProd()">Add to Cart</button>
    </div>
<?php } ?>

JAVASCRIPT

function addProd() {
    var test=  document.getElementsByClassName('test').innerText;
    alert(test);
}

Advertisement

Answer

The p tag is not a object with value attribute, you should use:

/* to get unformated text content, including all elements in <p> tag like styles in text format, hidden elements etc. */
 var test=  document.getElementById('test').textContent;
    
/* or - to get the visible text from the <p> tag */
var test=  document.getElementById('test').innerText;
    
/* or - to get the all html included in the <p> tag */
var test=  document.getElementById('test').innerHTML;

but first of all you must change your PHP code, you generate multiple

tags with same ID, so there is no unique ID you can handle. So make them unique and try with:

PHP

<?php 
foreach($product as $prods) { 
$i=1;
 echo'<div class="prod">
          <p id="test'.$i.'">'.$prods['name'].'</p>
          <button type="submit" onclick="addProd('.$i.')">Add to Cart</button>
    </div>';
$i++;
} 
?>

JAVASCRIPT

function addProd(number) {
    var product_id='test'+number;
    var test=  document.getElementById(product_id).innerText;
    alert(test);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement