Reputation: 12129
I am writing a program in raw javascript. When a <p>
element is clicked I wish this to trigger a function which adds the price of the element to the total. Please see my code below.
JS
function loadJSONDoc()
{
var answer;
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
answer = JSON.parse(xmlhttp.responseText)
var items = answer[0].prices[0];
for(var index in items) {
var node = document.getElementById("orderList");
var p = document.createElement('p');
var price = items[index];
p.setAttribute("class", price)
var textnode = document.createTextNode(index + " price = " + price);
p.appendChild(textnode);
node.appendChild(p);
};
}
var total = 0;
var update = document.getElementsByTagName("p");
update.onclick = function(){
///code here to update total based on element id
}
After the JSON object has been returned and my html page has been updated it looks like this:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<ul id="orderList">
<p class="4.75">Cafe Latte price = 4.75</p>
<p class="4.75">Flat White price = 4.75</p>
<p class="3.85">Cappucinoprice = 3.85</p>
</ul>
<script src="js/getData.js"></script>
</body>
</html>
I am able to target one <p>
element by using the following code, however I am looking for a solution whereby my function will trigger if I click on ANY <p>
element, which will in turn update the total based on the value of such <p>
element's class. I hope this makes sense.
var update = document.getElementsByTagName("p")[0];
update.onclick = function(){
///code here to update total based on element id
}
Thanks, Paul
Upvotes: 0
Views: 1330
Reputation: 21575
You will need to bind each item in document.getElementsByTagName("p")
. You are only doing it for the first one. For example:
var update = document.getElementsByTagName("p");
for( var i = 0; i < update.length; ++i ) {
update[i].onclick = function() {
//code here to update total based on element id
}
}
Note: You can access the value of the <p>
elements class by doing this.className
inside the onclick
function.
Upvotes: 1