0

I currently trying to change the color of the div when onclick the but fail , i using "postid" instead of using id and class cause it need to change the color of the div that onclick only

$(function () {
  $('.like').click(function () { likeFunction(this); });

});


function likeFunction(caller) {
  var postId = caller.parentElement.getAttribute('postid');
  $.ajax({
      type: "POST",
      url: "rate.php",
      data: 'Action=LIKE&PostID=' + postId,
      success: function () {}
  });
}
<div class="post" postid="10">
    <input type="button" class='like' value="LikeButton" /> </input>

</div>

4
  • 1
    How are you trying? I see 2 HTML elements, but no script. Can you show your attempts? Commented Jul 11, 2021 at 17:25
  • Please provide the code, what you have tried, I only see HTML. Commented Jul 11, 2021 at 17:25
  • What have you tried with your JavaScript so far? Commented Jul 11, 2021 at 17:25
  • Have you tried using data-* attributes instead? Commented Jul 11, 2021 at 17:29

1 Answer 1

1

You can reference $(this) in your likeFunction, and use a class to change the color.

$(function() {
  $('.like').click(likeFunction);
});

function likeFunction() {
  $(this).addClass('clicked')
  var postId = $(this).parent().attr('postid');
  $.ajax({
    type: "POST",
    url: "rate.php",
    data: 'Action=LIKE&PostID=' + postId,
    success: function() {}
  });
}
.clicked {
  background: #f00;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post" postid="10">
  <input type="button" class='like' value="LikeButton" /> </input>

</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.