Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, i have a JQuery function. Recently the needs changed and now instead of a single button we will have many. After trying it out there is a problem, no matter what button you click JQuery retrieves the data from the first button. It needs to be modified to get it from the one instance that is being clicked.

(function($) {
  $(".content-button").click(function(e) {
    e.preventDefault();

    var $contentWrapper = $("#content-wrapper");
	var postId = $contentWrapper.data("id");

    $.ajax({
        url: "/direct.php",
        type: "POST",
        data: {
          "post_id": postId   	  
        },
      })
      .done(function(data) {
      	$contentWrapper.html('');
        $contentWrapper.append(data);
      });
  });
  $(".content-button").mouseup(function(e) {
	  if (e.which == 1) {
      $(".content-button").hide();
    }
  });
})(jQuery);


What I have tried:

I think i have to use (this) but all i tried failed, i don't understand JQuery very well.
Posted
Updated 29-Oct-17 4:45am
Comments
Kornfeld Eliyahu Peter 29-Oct-17 10:14am    
Your HTML may help understand the problem...

1 solution

Move the id that relates to each button into the button itself and read it using "this" which represents the button that fired the event

<form id="form1" runat="server">
    <input type="button" class="content-button" value="One" data-id="1" />
    <input type="button" class="content-button" value="Two" data-id="2" />
</form>

<script>
        $(document).ready(function () {
            $(".content-button").click(function (e) {
                e.preventDefault();

                var postId = $(this).data('id');
                alert(postId);
            });
        });
</script>
 
Share this answer
 
Comments
Member 13491888 29-Oct-17 10:57am    
Worked well!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900