Search code examples
jqueryfindjquery-selectors

Get the value of an input from a button


Assuming I have this code :

...
<tr>
  <td align="right">
    <button type="button" class="btn btn-default editCustomer"><i class="fa fa-edit"></i></button>
  </td>
  <input type="hidden" name="usr_firstname" value="Franck">
</tr>
...

How to get the value of usr_firstname input ?

I already tried a couple of things like this:
- usr_firstname = $(this).closest('input[name="usr_firstname"]').val();
- usr_firstname = $(this).find('input[name="usr_firstname"]').val();


Solution

  • Your two elements are in different parts of the tree, so find the closest common ancestor then find down.

    usr_firstname = $(this).closest('tr').find('input[name="usr_firstname"]').val();
    

    Note: It is not valid HTML for your hidden input to be directly under a TR. Most browsers will tolerate it, but it should go elsewhere (e.g. inside the TD).

    Suggestion:

    I would suggest you instead inject the hidden values as data- attributes on the rows.

    <tr data-firstname="Franck">
      <td align="right">
        <button type="button" class="btn btn-default editCustomer"><i class="fa fa-edit"></i></button>
      </td>
    </tr>
    

    Then the code becomes just this:

    usr_firstname = $(this).closest('tr').data('firstname');