user3578396
user3578396

Reputation: 1

Get different values with same id in javascript

Html

<c:forEach var="legList" items="${legList}">/* iterating over ledger name and 
                                                  ledger id */                  
   <tr>
        <td>
        <input type="hidden" class="legid" name="legid" id=legid
        value=${legList.ledgerId}>
        <a onclick=display(document.getElementById('legid').value)
        href='#myModal' role="button" data-toggle="modal">${legList.ledgerName}</a>
        </td>
    </tr>

Javascript

var display = function(id){
alert(id);  //want to get id of clicked ledger name
}

But here problem is I'm getting same id on clicking all links and I know why it is happening because we can not get values with same id. so my question is how I can get different Id's here when id is changing inside for loop.Hope I am clear with my question.

Upvotes: 0

Views: 1001

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

ids must be unique in the document. If you break that rule by having multiple elements with the same id, the results are officially undefined (although in practice browsers give you the first one when you use getElementById).

Instead, use the fact that your a element instance is available as this within the onclick, and use that to find the input next to it with the DOM (perhaps using previousElementSibling in this case):

<a onclick="display(this.previousElementSibling.value)" ...

Example:

function display(value) {
  alert("value is: " + value);
}
<table>
  <tbody>
    <tr>
      <td>
      <input type="hidden" class="legid" name="legid" value="value1">
      <a onclick=display(this.previousElementSibling.value)
      href='#myModal' role="button" data-toggle="modal">Value 1</a>
      </td>
    </tr>
    <tr>
      <td>
      <input type="hidden" class="legid" name="legid" value="value2">
      <a onclick=display(this.previousElementSibling.value)
      href='#myModal' role="button" data-toggle="modal">Value 2</a>
      </td>
    </tr>
    <tr>
      <td>
      <input type="hidden" class="legid" name="legid" value="value3">
      <a onclick=display(this.previousElementSibling.value)
      href='#myModal' role="button" data-toggle="modal">Value 3</a>
      </td>
    </tr>
  </tbody>
</table>


In general, I'd suggest not using onclick, but instead using modern event handling or one of the many popular MVC-style frameworks instead.

Upvotes: 2

Related Questions