Patrick_Cork
Patrick_Cork

Reputation: 51

show/hide child elements of <li> with javascript

I have a razor loop on my .cshtml page in my mvc 4 project and I need to show hide the children of a list within this razor loop. The code works for the first element but not for the rest.

.cshtml code

<ol>
    @foreach (var Name in (List<string>)ViewData["Names"])
    {
        <li onclick="makevisible();" ondblclick="makeinvisible();">
            @Name
            <ul id="list" class="list">
                <li>childWichNeedsToBeHidden</li>
            </ul>
        </li>
    }
</ol>

My javascript: function makevisible() {$('#list').show();} and: function makeinvisible() {$('#list').hide();}

My css: .list {display:none;}

EDIT

my new .cshtml code

    @{
      int i = 0;
      foreach (var Name in (List<string>)ViewData["Names"])
      {
          i++;
          <li onclick="makevisible();" ondblclick="makeinvisible();">
            @Name
             <ul class="list" id="@i">
                <li>childWichNeedsToBeHidden</li>
             </ul>
          </li>
      }
    }

So now each ul has a unique id. But I do not know what my javascript should be. I can show hide a specific child ul like the third one with:

        function makevisible() {
            $('#3').show();
        }
        function makeinvisible() {
            $('#3').hide();
        }

how do I make the #3 a variable so that i can show hide any child ul i want?

Upvotes: 0

Views: 2963

Answers (2)

K D
K D

Reputation: 5989

<ol>
    @foreach (var Name in (List<string>)ViewData["Names"])
    {
        <li class="parentLI" onclick="makevisible();" ondblclick="makeinvisible();">
            @Name
            <ul class="list">
                <li>childWichNeedsToBeHidden</li>
            </ul>
        </li>
    }
</ol>

And your script should be

<script type="text/javascript">
 $(function(){

  $(".parentLI").click(function(){
    $(this).closest("ul.list").hide();
});

});
</script>

Bind the dblclick event in the same way

Upvotes: 0

Yograj Gupta
Yograj Gupta

Reputation: 9869

You should try with

function makevisible() {
    $(this).find('.list').show();
}

function makeinvisible() {
    $(this).find('.list').hide();
}

you should not use same id for ul in foreach.

Upvotes: 2

Related Questions