I’ve been struggling with this for two days, obviously because I have a very little knowledge in jQuery / Javascript, and I think I’ve searched thoroughly for so many times but didn’t get the answer that I need.
I’m working with a WordPress loop, each loop item has: a span with a class, and a link to trigger an update via jQuery to that span’s value / content.
What I have by far is: when I click a trigger-link – let’s say on the first loop-item, ALL of the span’s value / content on ALL of item loop is updated. What I’m trying to achieve is as simple as: when I click a trigger-link on the first loop-item, it update the span’s value / content on that loop-item only.
Here’s the HTML:
<div class="loop-item>
<span class="count">123</span>
<span><a class="update"></a></span>
<p>some text</p>
</div>
<div class="loop-item>
<span class="count">123</span>
<span><a class="update"></a></span>
<p>some text</p>
</div>
<div class="loop-item>
<span class="count">123</span>
<span><a class="update"></a></span>
<p>some text</p>
</div>
<div class="loop-item>
<span class="count">123</span>
<span><a class="update"></a></span>
<p>some text</p>
</div>
Here’s the jQuery:
$(document).ready(function(){
$(".update").click(function(){
var countVal = $(".count").text();
var nuVal = countVal + 1;
$(".count").text(nuVal);
});
});
I know it’s an entirely wrong jQuery code. I’m willing to learn and hoping someone here is willing to help to get it right.
Thanks.
UPDATE:
The working jQuery codes are as follow (modified the nuVal variable):
$(document).ready(function(){
$(".update").click(function(){
var countSpan = $(this).closest(".loop-item").find(".count");
var countVal = countSpan.text();
var nuVal = parseInt(countVal) + 1;
countSpan.text(nuVal);
});
});
Thank you!
this one is easy enough, i see two main issues first what you are saying here is:
is changing all items with the class count.
second your loop item divs are missing a quote at the end of the class:
if i understand correctly you are looking to accomplish this: on click of a link element with class “update” change the value of only the span element of class “count” within that same loop-item div.
here is how we can accomplish that task:
Inside the click() callback,
$this
will refer to the<span class="update">
. So you can select its grandparent as a base to do this:Try this;
You basically need to grab the parent of the item you have clicked and use that to select the inline elements you need.