javascript - Altering Specific Text with jQuery -
here html/php:
<p> <span data-good="<?php echo $row['good']; ?>" data-wasvoted="<?php echo $row['wasvoted']; ?>" data-review="<?php echo $row['review_id']; ?>" class="upvote">votes (<span class="good"><?php echo $row['good']; ?></span>)</span> </p>
this looks mess, apologize test code.
to user in output:
votes (3) // 3 example number.
this clickable. want user click on it, , if have voted on this, 3 becomes 2. if have not, 3 becomes 4. determined data-wasvoted
attribute. 1 if have , 0 if haven't. (there styling user can identify if have upvoted or not).
sending info server , getting need set up. can't figure out way grab right number since looped list of generated html. there string of dynamic vote buttons.
here jquery:
var review_id = $(this).data('review'); var was_voted = $(this).data('wasvoted'); var vote_total = $(this).data('good'); var new_text = $('.good'); $.ajax({ url : "php/reviews_upvote.php", type : "post", datatype : "json", data : { reviewid : review_id }, success : function(data) { if (was_voted == 1) { vote_total = vote_total - 1; new_text.text(vote_total); } else { vote_total = vote_total + 1; new_text.text(vote_total); } } });
the first problem var new_text
. it's based on class
repeated on , on again. if click one, vote numbers change on page, not 1 dealing with. how can identify unique attribute of 1 need?
the second issue; since user can vote 1 -- need dynamically change was_voted
var 0 if 1, or 1 if 0.
edit: added html rendered after php
called.
<span data-good="2" data-wasvoted="1" data-review="2582" class="upvote"> votes (<span class="good">2</span>) </span>
data-good
vote total.
if logic handled inside click event .
1st problem - use target element.
2nd problem - use same context change data attribute
var $this = $(this), review_id = $this.data('review'), was_voted = $this.data('wasvoted'), vote_total = $this.data('good'), new_text = $('.good'); $.ajax({ url : "php/reviews_upvote.php", type : "post", datatype : "json", data : { reviewid : review_id }, success : function(data) { if (was_voted == 1) { vote_total = vote_total - 1; $this.data('wasvoted', 0); } else { vote_total = vote_total + 1; $this.data('wasvoted', 1); } $this.find('.good').text(vote_total); } });
Comments
Post a Comment