Right now my website's voting system is working, except for the fact that when i like something, it'll change the color of the button (via the this.* commands in the jquery/javascript file),
but then when i click on the opposing button [the dislike button] it'll color the dislike button and keep the like button colored, effectively having both buttons colored until i refresh the page
...
How can i grab the button element that is next to the clicked element?
So far my js code is as follows:
$(function() {
$("body").on("click", ".vote", function (event) {
var clicked = $(this);
var request = $.ajax({
url: $(this).attr("href"),
dataType: 'json'
});
event.preventDefault();
request.done(function (data) {
if (data['vote'] == 1 || data['vote'] == -1)
{
clicked.children("button").attr('class', 'btn btn-primary btn-sm');
}
else if (data['vote'] == 0)
{
clicked.children("button").attr('class', 'btn btn-default btn-sm');
}
});
request.fail(function (data) {
alert("Voting failed!");
});
});
});
and my view code [multiple instances of these as there are multiple boxes with a like/dislike pair of buttons.]:
<!-- Like button -->
<a style="text-decoration: none" class="vote" href="<?php base_url(); ?>vote/like/<?php echo $row['id']; ?>">
<button type="button" class="btn btn-default btn-sm">
<span style="font-size: 3em" class="glyphicon glyphicon-thumbs-up"></span>
</button>
</a>
<!-- Dislike button -->
<a style="text-decoration: none" class="vote" href="<?php base_url(); ?>vote/dislike/<?php echo $row['id']; ?>">
<button type="button" class="btn btn-default btn-sm">
<span style="font-size: 3em" class="glyphicon glyphicon-thumbs-down"></span>
</button>
</a>
Wrap a div around each pair of vote buttons
<div>
<!-- Like button -->
<a style="text-decoration: none" class="vote" href="<?php base_url(); ?>vote/like/<?php echo $row['id']; ?>">
<button type="button" class="btn btn-default btn-sm">
<span style="font-size: 3em" class="glyphicon glyphicon-thumbs-up"></span>
</button>
</a>
<!-- Dislike button -->
<a style="text-decoration: none" class="vote" href="<?php base_url(); ?>vote/dislike/<?php echo $row['id']; ?>">
<button type="button" class="btn btn-default btn-sm">
<span style="font-size: 3em" class="glyphicon glyphicon-thumbs-down"></span>
</button>
</a>
</div>
Then modify the request done call to uncolor both buttons before coloring the clicked button.
request.done(function (data) {
clicked.parent().find('button').attr('class','btn btn-default btn-sm');
if (data['vote'] == 1 || data['vote'] == -1)
{
clicked.children("button").attr('class', 'btn btn-primary btn-sm');
}
});