0

Let's look at table of inputs and buttons:

<tr>
  <td>
    <input type=\"number\" name=\"name1\">
  </td>
  <td>
    <button type=\"button\" class=\"button\">Button</button>
  </td>
</tr>
<tr>

The table is bigger, and contains many rows of the same structure as above.

How to, using jquery, get value of input next to the button on click?

I can access the field by using

$(document).on('click', '.button', function() {
    $(this).parent().prev() // this is the input type
});

but calling .val() on it doesn't work.

1 Answer 1

4

If you have a large table and you are going to be doing this a lot, I would suggest using HTML5 data attributes to link the button with the input field:

<tr>
  <td>
    <input id="input-1" type=\"number\" name=\"name1\">
  </td>
  <td>
    <button data-input=\"#input-1\"type=\"button\" class=\"button\">Button</button>
  </td>
</tr>
<tr>

Notice the id attribute on the input matches the data-input attribute on the button. Now you can do something like this:

$('button').on('click', function() {
    var input = $(this).data('input');
    var value = $(input).val();

    // Do something with the value
});

Update

If the relationship is not one-to-one, you would have to modify the structure a bit. You couldn't use the id attribute, since id's must be unique. Instead, you could give each input a data attribute, such as:

<input data-group="1" type=\"number\" name=\"name1\">

And your button would have a corresponding data attribute:

<button data-input=\"1\"type=\"button\" class=\"button\">Button</button>

Then in your click handler, you could do this:

$('button').on('click', function() {
    var input_group = $(this).data('input');
    var inputs = $('input[data-group="' + input_group + '"]');
    var values = [];

    // Read the values into an array
    $.each(inputs, function(i, input) {
        values.push(input.val());
    });

    // Do something with the values...
});
Sign up to request clarification or add additional context in comments.

1 Comment

Would this method work if it wasn't one-to-one connection, but let's say 2 or 3 inputs per one button?

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.