Anthony Don
Anthony Don

Reputation: 157

How to get jquery .closest() to work in this particular situation?

Ok I been trying to use the jquery .closest() function. I've done some research but it must be some logic that I can't figure out and it's driving me nuts. So here is the code please help.

<div class="tablecontainer">

mvcpartial with

<div class="emptycontainer"><p>no data in table</p></div>
<div class="populatedcontainer"><table><thead><tr></tr></thead>
    <tbody>
        <tr>
            <td><a onclick="deleteRow(this, @Model.ID)"></td>
        </tr>
    </tbody>
</table>
</div>

endpartial

</div>

The deleteRow function takes in the parameter (that, id). I am able to delete the row but what I am having trouble with is fading out the div.populatedcontainer and fading in div.emptycontainer when the table is empty. I tried

var $table = $(that).closest('div.tablecontainer');
$('div.populatedcontainer', $table).fadeOut('slow');
$('div.emptycontainer', $table).fadeIn('slow');

I tried testing if the selector was able to locate div.tablecontainer with

if ($table.length > 0) {
    console.log("located tablecontainer");
}

but that did not show up in console during debug. There are multiple sets of div.tablecontainer on the page if that matters.

I tried var table; (without the $).

I tried var $that = $(that);

I tried putting this outside of the "if table is empty logic" but it still doesn't work

Edit: per Felix Kling request

the tr has a link that calls the following function when clicked

onclick="deleteRow(this, @Model.ID)

and the function takes the parameter like

function deleteRow(that, id){
   tried to do stuff like find the right div and fadeIn/fadeOut here (example attempts above)
}

Thanks for all the answers. Especially the ones with alternative method look promising. I'll have to try and see which ones work tomorrow and update this post.

Upvotes: 2

Views: 108

Answers (3)

reggaemahn
reggaemahn

Reputation: 6648

This method doesn't use .closest() but would help you accomplish the task. Assuming that you have got the element stored in a variable called 'that', here is what you need to do:

$(that).parent(".populatedContainer").siblings().fadeIn();
$(that).parent(".populatedContainer").fadeOut();

Upvotes: 0

Travis J
Travis J

Reputation: 82287

jsFiddle Demo

If all of your structure is similar, then you can just use prev.

var $table = $(that).parents('.populatedcontainer:first');
$table.fadeOut('slow').prev('.emptycontainer:first').fadeIn('slow');

Upvotes: 1

Aguardientico
Aguardientico

Reputation: 7779

Well, without using closest but parents

var $table = $(that).parents('div.tablecontainer').eq(0);
$table.find('div.populatedcontainer').fadeOut('slow');
$table.find('div.emptycontainer').fadeIn('slow');

Upvotes: 0

Related Questions