0

Really simple question. Why doesn't

<div class="plus-button" onclick="voteUp(' . $postid . ')" data-postid="' . $postid . '" name="like">+ ' . $voterow['totalupvotes'] . '</div>

work with

<script type="text/javascript">
function voteUp(postid){
        var postid = postid;
        $(this).siblings('.minus-button').removeClass('disliked');    
        $(this).toggleClass('liked');

        $.ajax({
            type:"POST",
            url:"php/votesystem.php",
            dataType : 'html',
            data:'act=like&postid='+postid,
            success: function(data){
                $('.plus-button').html(data);
                alert("Liked with id "+postid);
            }
        });
}

</script>

The div line works fine. The problem is that $(this) in the java/jq script is not recognized as a specific div class.

I have tried using voteUp(this) and didn't get it to work. Also tried using

var postid = $(this).data('postid');

but my alert msg then says undefined id instead of whatever id it should be.

2 Answers2

0

Remove the onclick and use jQuery to get the postid

$(function() {
  $(".plus-button").on("click",function() {
    var postid = $(this).data("postid");
    // $(this) is now the div clicked
    $(this).siblings('.minus-button').removeClass('disliked');    
    $(this).toggleClass('liked');
    .
    .
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Did that before I changed it to onclick. Onclick resolved the issue though. – Sindre Sørensen Sep 01 '14 at 08:11
  • I do not understand your comment. Use the event handling of jQuery instead of inline onclick and your problem is solved. It is the recommended way and you even save bandwidth by not having the onclick on each div – mplungjan Sep 01 '14 at 08:15
-1

instead of just calling voteUp( #postId) use the call method so voteUp.call(this, #postID);

<div class="plus-button" onclick="voteUp.call(this, ' . $postid . ')" data-postid="' . $postid . '" name="like">+ ' . $voterow['totalupvotes'] . '</div>

what you basically do here is that you change the context of the function or the "this" variable from the function prototype to the div dom object. more can found in the documentation below :)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call