Ignacio Chiazzo Ignacio Chiazzo - 1 year ago 67
Javascript Question

Create a List of button with generic id's in order to get any of them with getElementById. (Id dinamically)

I want to create dynamically the id's of the buttons into a list of buttons, in order to get any of the button using getElementById.

An example of the code using the same id :

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

The function onClickSeeProducts should looks like :

function onClickSeeProducts() {
button = document.getElementById("nameCategory").innerHTML;

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