I am using MVC 4 with Razor view engine.
I want to display a nested unordered list comprised of years as parents and months as children.
Consider the following HTML:
<div>
<ul>
@foreach (var yr in Dates.Select(x => x.Year).Distinct())
{
<li><a href="#" class="parent">@yr</a></li>
<ul class="child" style="display: none">
@foreach (var mo in Dates.Where(x => x.Year == yr).Distinct())
{
<li id="@yr"><a href="#" class="submit-link" id="@mo.Month">@mo.ToString("MMMM")</a></li>
}
</ul>
}
</ul>
</div>
I have added the following script to make the “.child” (dis)appear when I click on “.parent” anchor.
<script type="text/javascript">
$(function () {
$(".parent").click(function () {
$(this).closest("ul").find(".child").toggle("fast")
return false;
});
});
</script>
However it toggles ALL “.child” items in the document. How to make it toggle only the child one?
Your html is invalid: you can’t have a
<ul>element nested directly within another<ul>.Your
<ul class="child">should be within the same<li>element as the corresponding anchor element:Then you can do this:
The way you had it,
$(this).closest("ul")goes up to the top-level<ul>, so then when you use.find(".child")it finds all elements with that class anywhere in the top-level<ul>.