0

I have got the following HTML table...

<table>
  <thead>
    <tr>
      <th>Nr.</th>
      <th>Name</th>
      <th>Info</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Laura</td>
      <td><input type="hidden" value="1"><a href="#" class="info">Info</a></td>
    </tr>
    <tr>
      <td>2</td>
      <td>Sabrina</td>
      <td><input type="hidden" value="2"><a href="#" class="info">Info</a></td>
    </tr>
  </tbody>
</table>

How can I get with jQuery the value of the hidden input field, when the link is clicked?

$(".info").click(function() {
  // Here I need to find out the value...
});
1

2 Answers 2

3

Here's how you do it :

$(".info").click(function(e) {
  //just in case, will be useful if your href is anything other than #
  e.preventDefault();
  alert($(this).prev('input[type="hidden"]').val());
});

prev method will search for the previous element, which is where your input[hidden] is.

And its href, not hre, in the <a/> tags.

Sign up to request clarification or add additional context in comments.

9 Comments

Don't forget to return false; or e.preventDefault();.
Hmm..just added that..didnt bother because the href was pointing to #
@FrédéricHamidi: An href of # doesn't magically stop the default action. # is used to jump around to different anchors in the page. # will jump to the top of the page and add # to the URL, unless you stop the default action.
@hungerpain: Read my previous comment. # doesn't magically stop the default action.
@FrédéricHamidi: I only knew that because I recently forgot about this and wondered why my page kept jumping to the top.
|
2

You can also use attributes <a href="#" data-hidden="1" class="info"> don't need use hidden fields

$(".info").click(function(e) {
  e.preventDefault();
  alert($(this).data('hidden')); // or $(this).attr('data-hidden');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.