Popescu Marian
Popescu Marian

Reputation: 93

jquery onclick hide/show div

I have a php file that show the friends requests, lets say there are 4 requests. I want to hide the div with the class "request_buttons" when the user clicks on accept or refuse link but the problem is that it is hiding the other 3 divs too and I want to hide only the div where the link was pressed.

My html code is:

<div class="request_buttons">
   <a href="#" onclick="accept(<?php echo $cerere['id']; ?>)">accept</a>
   <a href="#" onclick="refuse(<?php echo $cerere['id']; ?>)">refuse</a>
</div>
<span class="result"></span>

and the javascript is:

function accept(id)
{
    $.ajax({
       type: "POST",
       url: "request.php?action=accept",
       data: "id="+id,
       success: function(){
            $('.request_buttons').hide();
            $('.result').html('Request accepted');
       }
     });
}

LE: using the code provided by Royi Namir I came up to a sollution (by mistake). I modified the html to this:

<div id="2">    
     <div class="request_buttons">
    <a href="#" onclick="accept(2)">accept</a>
    <a href="#" onclick="refuse(2)">refuse</a>
     </div>
  <div class="result"></div>            
</div>

and the jquery with this:

function accept(id)
{
t = $('#'+id);
    $.ajax({
       type: "POST",
       url: "request.php?action=accept",
       data: "id="+id,
       success: function(){         
       $(t,'.result').first().html('Accepted');
       }
     });
}

And it works, the div "request_buttons" dissapear and the message appears. I don't know how but it works!

Upvotes: 1

Views: 3778

Answers (3)

Royi Namir
Royi Namir

Reputation: 148624

div class="request_buttons">
   <a href="#" onclick="accept(this);">accept</a>
   <a href="#" onclick="refuse(this);">refuse</a>
</div>

function accept(obj)
{
t = $(obj);

    $.ajax({
       type: "POST",
       url: "request.php?action=accept",
       data: "id="+id,
       success: function(){
            t.parent(".request_buttons").hide();
            $('.result').html('Request accepted');
       }
     });
}

Upvotes: 3

Umesh Patil
Umesh Patil

Reputation: 10695

You can use the jquery parent function for this. Try $(this).parent().hide()

Upvotes: 0

techfoobar
techfoobar

Reputation: 66693

In your code, replace

$.ajax({
   type: "POST",
   url: "request.php?action=accept",
   data: "id="+id,
   success: function(){
        $('.request_buttons').hide();
        $('.result').html('Request accepted');
   }
 });

with

$.ajax({
   type: "POST",
   url: "request.php?action=accept",
   context: $('#'+id),
   success: function(){
        $(this).parents('.request_buttons').hide();
        $('.result').html('Request accepted');
   }
 });

Upvotes: 2

Related Questions