Need to check the value of the hidden input field associated with the click of the element (multiple with the same name)

The title is not so clear, so let me see if I can explain what I am doing.
I am listing user posts and they have a comment button with those posts.

What I need to do is capture when a button like (t20>) is clicked and then grab the post id from the hidden input field and use it to post to a PHP script.

PHP does all the checks if they are friends, the privacy level is correct, etc. before posting this information to the database, but currently I am just creating javascript / jquery when the message (designation of each js / DOM element according to post id), but it's not very efficient and looks messy when looking at the source (but that's the only way to make it work).

I want to be able to use an external javascript file to check when only the type button was clicked and find out which message to like and work that way.

I have been doing this for quite some time and as far as I know this

may work, but I had no luck. I am creating multiple posts on the same page using a loop foreach()

, so the element names / ids / classes are the same.


To understand a little better, here's an example of what a message might look like:
<div class="feedPost">
    <img src="#" class="feedProfile"/>
    <a href="#" class="feedName">FirstName LastName</a>
    <div class="feedPostBody">Hello, world!</div>
    <input type="hidden" value="24772" name="feedPostID">
    <span class="feedLikeButton">Like</span> | <a href="#">Comment</a> | 2 mins ago
</div>

      

and using javascript / jquery I want to be able to do something like this in an external js file:

$('.feedLikeButton').on('click',function(){
  var post_id = 0; //I need to get the ID from the post that the like button is related to.
  //If I just did $('.feedPostID').val() it wouldn't work
  $.post("https://mysite/path/to/like.php", {post: post_id}).done(function(data){
    if(data == "success"){
      //This will set text from "Like" to "Unlike"
      //Again, I can't just do $('.feedLikeButton') to access
      //I guess I could do this.innerHTML? Would still need to access feed post id
    } else {
      //Probably will just flash error to user if error, or something similar
    }
  });
});

      

+3


source to share


1 answer


You should get the button you like

var likeButton = $(this);

      

Then get the container

var container = likeButton.parent();

      

Then find the hidden field



var idInput = container.find('[name="feedPostID"]');

      

Then get the value:

var id = idInput.val();

      

With all these links, you can do whatever you want.

+1


source







All Articles