Jquery Closest From Element Value
Asked Answered
L

3

5

Im trying to get a form element value using closest. Here some example code.

<table>
  <tr>
    <td>Hour <input type="input" value="12" name="data[hour]" class="hour" /></td>
    <td>Minute <input type="input" value="12" name="data[minute]" class="minute" /></td>
    <td><a href="#" class="add-data">Add Row</a></td>
  </tr>
</table>

See I cant serialize the form because it is part of a large form so I need to grab each input closest to the add row link as yo will be able to add multiple rows.

I have tried

var hour = $(this).closest('.hour').val();    
var hour = $(this).closest('input', '.hour').val();
var hour = $(this).closest('input[name="data[hour]]").val();

Any ideas how I can get the form values ?

Thanks in advance

Ledford answered 8/7, 2010 at 16:4 Comment(0)
D
13

Assuming you have just one .hour element per tr, this will do it:

var hour = $(this).closest('tr').find('.hour').val();

closest will:

Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

So, you need to go up to the tr, and from there find the .hour descendant.

Demand answered 8/7, 2010 at 16:7 Comment(1)
Thats the one perfect. Thank youLedford
A
2

To expand on Karim79's answer:

.closest() moves up the DOM tree until it finds a match. It will not work with elements at the same level - such as in your case (all elements have a td as a parent) .

http://api.jquery.com/closest/

To use closest() in your situation, you'd have to use (which is a bit of overkill here):

$(this).closest("tr").find(".hour").val();
Aggrandize answered 8/7, 2010 at 16:12 Comment(0)
E
0
$(".addToCart").on('click', function() {
  var item_id = $(this).closest('div').find('#item_id').val();
  var labtest_id = $(this).closest('div').find('#labtest_id').val();
  var vendor_id = $(this).closest('div').find('#vendor_id').val();

  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });
});
Epicritic answered 14/6, 2023 at 10:41 Comment(2)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Emmerich
You should add explanation.Megacycle

© 2022 - 2024 — McMap. All rights reserved.