1

I have a for-loop that creates a list. Each item on the list has a hidden input and function as below.

<input type="hidden" id="network-id" name="network_id" value="1">
<button type="button" onclick="transfer(someId);"></button> 

I'm using my JS code to read the hidden input in transfer function.

networkId = $("#network-id").val();

But since each element ID is the same, it only reads the first "network-id" element on the list.

What is the best way to read each element?

ratib90486
  • 89
  • 1
  • 7
  • 2
    IDs are supposed to be unique. If you have more than one with the same name, JS will only grab the last one. You need to figure out a way to give these elements a unique ID as you build them in your loop – Major Productions Jul 08 '23 at 01:31

4 Answers4

1

Use a class name or just take the previous element sibling of each button.

function transfer(button){
  console.log(button.previousElementSibling.value);
}
<input type="hidden" class="foo" value="1">
<button type="button" onclick="transfer(this);">One</button> 

<input type="hidden" class="foo" value="2">
<button type="button" onclick="transfer(this);">Two</button> 

<input type="hidden" class="foo" value="3">
<button type="button" onclick="transfer(this);">Three</button> 
Alexis88
  • 297
  • 1
  • 11
1

It is generally not a good idea to use inline event handlers.

Id's should be unique, so you should use something else to identify fields/elements. I would suggest data-attributes.

Using data-attributes you don't even need a hidden input field to store a value. A value can be assigned directly to the button.

With that in mind, here is a minimal reproducable example to handle buttons using event Delegation and to read out the value from the buttons' data-attribute.

document.addEventListener(`click`, handle);

createSomeButtons();

function handle(evt) {
  if (evt.target.dataset.bttnid) {
    console.clear();
    console.log(`transfer value: ${evt.target.dataset.value}`);
  }
}

function createSomeButtons() {
  const bttns = [...Array(10)].map( (_, i) => {
    const bttn = document.createElement(`button`);
    bttn.dataset.bttnid = `${i + 1}`;
    bttn.dataset.value = `bttn ${i + 1}`;
    bttn.textContent = `transfer ${i + 1}`;
    return bttn.outerHTML; } );
  document.body.insertAdjacentHTML(`beforeend`, bttns.join(`<br>`));
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

Element IDs should be unique. You can adjust your code so that it gives each element the same class instead or give each element a unique id.

Tim
  • 112
  • 6
0

Make a Function and add ++ in every time after that when loop run it run with the function.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 10 '23 at 08:59