Ignacio Chiazzo Ignacio Chiazzo - 7 months ago 13
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>
</div>
}


The function onClickSeeProducts is :

function onClickSeeProducts() {
msg = document.getElementById("nameCategory").innerHTML;
$.getJSON(uriPCategory).done(function (data) {
$.each(data, function (key, item) {
alert(JSON.stringify(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

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;
...