1

I am able to show/hide div onclick successfully. But onclick div display for a second and page get refresh. I have use javascript. Code:

       @{var Count = 0;}
 foreach (var commentlist in Model.Comments.Where(x => x.CommentParentID == 0))
  {
 <div id="@Count" style="display: none;">
<input type="submit" id="reply" class="reply-link" onclick="return showHide(@Count);" value="Reply" />
 @{Count++; }
</div>
}


<script type="text/javascript">
 function showHide(Count) {
        var ele = document.getElementById(Count);
        if (ele.style.display == "block") {
            ele.style.display = "none";           
        }
        else {
            ele.style.display = "block";
        }
    }
</script>
Netra Wable
  • 11
  • 1
  • 4

2 Answers2

0

It happens because your page is being submitted. Try using <input type="button"...> instead of <input type="submit"...>

Difference here: Difference between <input type='button' /> and <input type='submit' />

And your controls id can't start with a number and must be unique:

@{var Count = 0;}
foreach (var commentlist in Model.Comments.Where(x => x.CommentParentID == 0))
{
    <div id="div_@Count" style="display: none;">
        <input type="submit" id="reply_@Count" class="reply-link" onclick="return showHide('mydiv_@Count');" value="Reply" />
        @{Count++; }
    </div>
}
Community
  • 1
  • 1
Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
0

If the submit button is inside a <form> you need to return false from the showHide if you don't want the page to get submitted after clicking on it:

<script type="text/javascript">
function showHide(Count) {
    var ele = document.getElementById(Count);
    if (ele.style.display == "block") {
        ele.style.display = "none";           
    }
    else {
        ele.style.display = "block";
    }

    return false; // <-- that's important to prevent the page from submitting
}
</script>

Also please bear in mind that an id attribute cannot start with a number in HTML. So please fix your markup:

@{var Count = 0;}
foreach (var commentlist in Model.Comments.Where(x => x.CommentParentID == 0))
{
    <div id="mydiv_@Count" style="display: none;">
        <input type="submit" id="reply" class="reply-link" onclick="return showHide('mydiv_@Count');" value="Reply" />
        @{Count++; }
    </div>
}


<script type="text/javascript">
function showHide(id) {
    var ele = document.getElementById(id);
    if (ele.style.display == "block") {
        ele.style.display = "none";           
    }
    else {
        ele.style.display = "block";
    }
    return false;
}
</script>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928