HelpASisterOut HelpASisterOut - 8 days ago 6
C# Question

how to Javascript toggle ID of div generated on runtime

I am sending a Model to a View in MVC,

and for each "Person" in my Model, I want to create a button that says "Show Details", when the user clicks it, a div with more information about that person toggles.

I am generating a

a href
and
div
id assigned to each person ID like the following:

foreach (var person in Model.Persons)
{
<div>
<a href="#" id="@Html.Raw("showDetails-" + @person.id)">Show Details</a>
</div>
<div id="@Html.Raw("detailsDiv-" + @person.id)">
<!--Content Here -->
</div>

}


I want to create the javascript that toggles on a click event

So I want to write this script but with the unique id for each person:

I want to get the id of the div that needs to be toggled.

I tried writing the script inside the foreach loop so I can be able to read the @person.id value, but it didnt work:

<script>
$(document).ready(function () {
$("#showDetails-@person.id").click(function () {
$("#details-@person.id").toggle();
});
});
</script>


Can anyone help?

Answer

put a class to your links like class="showDetails".

Now you Can create a global Event for all that links:

$('.showDetails').click(function(e) {
   var id = this.id // extract id.. split with '-' or whatever..
   $('#details-' + id).toggle();
});
Comments