0

Im trying to display multiple charts.

Right now, I have <canvas id="pie-chart"> inside a loop and document.getElementById("pie-chart") will only return the first element with that id. How do I create a dynamically html attribute?

<table class="table">
                    <tr>
                        <th>
                            Questions
                        </th>
                    </tr>
                    @foreach (var question in (List<Testv3.Models.MyViewModel>)ViewData["questionlist"])
                    {
                        <tr>
                            <td>
                                @question.Question
                                <br />
                                <div class="chart">
                                    <canvas id="pie-chart"></canvas>
                                </div>
                            </td>
                        </tr>
                    }
</table>

A part of my script section:

var ctx1 = document.getElementById("pie-chart").getContext("2d");
mj.e
  • 43
  • 2
  • 13

2 Answers2

0

I'm not totally sure what you are using to render your HTML since your code doesn't look like pure HTML to me. However, the answer stays the same, you can use the index of the loop as a part of your id to make it unique. Something like this:

<canvas id="pie-char-@id></canvas>

with @id is your index of the loop.

If your current renderer doesn't support that, you may want to add a counter outside of the loop, use that counter as part of your id. Then increase the counter at the end of the loop.

Tree Nguyen
  • 1,198
  • 1
  • 14
  • 37
  • Hello, I did this and now the ids are added dynamically but how about the script section? How do I rewrite `document.getElementById("pie-chart")`? – mj.e Feb 09 '18 at 06:47
  • What do you mean by that? Your question is unclear to me but if this solves your problem please consider accepting it as an answer. Try to ask atomic and clear questions. HTML5 Canvas, JavaScript, ASP.NET, it's not clear which part you're having problem with. Try to narrow down the problem (first make sure you know how ASP.NET directives work and take it from there). – Nader Ghanbari Feb 09 '18 at 06:56
-1

See Does ID have to be unique in the whole page?

The HTML Id needs to be unique in your whole HTML-Instance. Use "class" instead of "id".

Id is and was never designed to be used multiple times. Id is designed to be a unique identifier.

r4r3devAut
  • 90
  • 10