'Capture text inside a <p> 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);
}
Solution 1:[1]
I think you misspeled "teste" and you should use textContent for this.
var test= document.getElementById('test').textContent;
Solution 2:[2]
Since you are using inline bindings, I would suggest that you pass in the value you are trying to lookup, and cut out the middle man of trying to find it in another element.
<div class="prod">
<p class="test"><?php echo $prods['name'] ?></p>
<button type="submit" onclick="addProd('<?php echo $prods['name'] ?>')">Add to Cart</button>
</div>
There's no reason to lookup the value. Just give it to the method.
Solution 3:[3]
PHP
<?php
foreach($product as $key => $prods) {
echo'<div class="prod">
<p id="test'.$key.'">'.$prods['name'].'</p>
<button type="submit" onclick="addProd('.$key.')">Add to Cart</button>
</div>';
}
?>
JAVASCRIPT
function addProd(number) {
var test= document.getElementById('test'+number).innerText;
alert(test);
}
Solution 4:[4]
First of all, welcome to Stack Overflow. The problem you are facing is that .value isn't an attribute for <p> elements. Here are some alternatives:
.innerHTML; - not recommended due to XSS and other security issues.innerText;.textContent;
Also, your products will be duplicated as it is in a for loop, so use pass the this value.
Your JavaScript should look like:
function addProd(thingtoget) {
var test = thingtoget.innerText;
alert(test);
}
The function addProd(thingtoget) alerts the user the text of the product.
Then your php should have an onclick function passing on the this. So, your PHP should be:
<?php foreach($product as $prods) { ?>
<div class="prod">
<p id="test"><?php echo $prods['name'] ?></p>
<button type="submit" onclick="addProd(this.parentElement.querySelector('#test'))">Add to Cart</button>
</div>
<?php } ?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Agnitor44 |
| Solution 2 | Taplar |
| Solution 3 | Elakya |
| Solution 4 |
