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?
3
Answers
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.
Use a class name or just take the previous element sibling of each button.
To read each element in your list, you can modify the HTML code and JavaScript logic. Here’s a solution using a modified approach:
HTML code:
JS Code:
Explanation:
In the HTML code, we add a CSS class (network-id) to the hidden input elements instead of using the same ID for all elements. This allows us to select them using the class selector.
In the onclick attribute of each button, we pass this as an argument to the transfer function. This passes the button element itself to the function.
In the JavaScript code, $(button) wraps the button element as a jQuery object. Using .prev(‘.network-id’), we select the preceding sibling element with the class network-id, which is the corresponding hidden input element.
Finally, we can retrieve the value of the hidden input using .val() and assign it to the networkId variable. You can continue with the rest of your logic using this value.
By using this approach, you can read the hidden input value for each item in the list, even if they have the same class name.