Nitesh
Nitesh

Reputation: 1637

unable to get hidden field value using parent 's class name

My html code is-

<tr class="selected">
<td id="participantID">XXXXX1234</td>
<input type="hidden" value="000001234" id="taxID">
<td id="fullName">Y, X</td>
</tr>

Here, I want to get hidden field value. I can not use ID of hidden field to get its value because there are multiple rows which can contain hidden field with same ID as "taxID". I want to get this value using <tr> class name. i.e. selected.

I am using below code to get its value but it is giving me 'undefined' value.

var x = document.getElementsByClassName("selected")[0];
var y = x.getElementsByTagName("input")[0];
alert(y.value);

Alert statement shows undefined value. Am I missing something over here?

Upvotes: 0

Views: 630

Answers (3)

halfer
halfer

Reputation: 20335

(Posted solution on behalf of the OP).

After removing ID of hidden field, it is working fine. Edited code is:

<tr class="selected">
<td id="participantID">XXXXX1234</td>
<input type="hidden" value="000001234" id="taxID">
<td id="fullName">Y, X</td>
</tr>

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65883

First, you cannot have multiple elements in a document with identical id values. That will have to be altered and that alone may solve your problem.

Second, your HTML is invalid. The input must be inside of a td.

Next, there is no reason to use getElementsByClassName() or getElementsByTagName() when you are looking for just one element - it's wasteful because you wind up searching the entire document when you are only interested in one item.

Also, both of those methods return "live" node lists which require re-scanning the entire document every time their results are referenced. The use cases for that are limited.

Instead use .querySelector() when you want to find just one item based on any valid CSS selector and .querySelectorAll() when you want to find a set of matching elements.

Assuming these things are corrected, you can do this:

var x = document.querySelector(".selected td input[type=hidden]");
alert(x.value);
<table>
  <tr class="selected">
    <td id="participantID">XXXXX1234
     <input type="hidden" value="000001234" id="taxID">
    </td>
    <td id="fullName">Y, X</td>
  </tr>
</table>

Upvotes: 3

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

You need to have a table be the parent of a tr, then the DOM lookup will properly work. Also as noted by @Rory McCrossan you will want to wrap td tag around your input element:

var x = document.getElementsByClassName("selected")[0];
var y = x.getElementsByTagName("input")[0];
alert(y.value);
<table>
  <tr class="selected">
    <td id="participantID">XXXXX1234</td>
    <td><input type="hidden" value="000001234" id="taxID" /></td>
    <td id="fullName">Y, X</td>
  </tr>
</table>

Upvotes: 0

Related Questions