Ignacio Chiazzo Ignacio Chiazzo - 2 years ago 58
HTML Question

Create a List of button and get them with getElementById. (Id dinamically)

i have a list of button

@foreach (var cat in Model) {
<div class="list-group">
<button id="nameCategory" onclick="onClickSeeProducts()" >@cat.Name</button>

The function onClickSeeProducts is :

function onClickSeeProducts() {
msg = document.getElementById("nameCategory").innerHTML;
$.getJSON(uriPCategory).done(function (data) {
$.each(data, function (key, item) {

The problem is msg is always equal to the first value. If I click on any of the button the msg is always the same.

Answer Source

Ids must be unique, since all your buttons have the same id, there is no way to know which button you want to target by use of id.
An easier way would be to just pass the button as an argument to the function.

... onclick="onClickSeeProducts(this)" ...
function onClickSeeProducts(button) {
   msg = button.innerHTML;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download