JQuery Closest on element value

I am trying to get the value of a form element using the closest. Here is a sample 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 cannot serialize the form because it is part of a large form, so I need to grab every input closest to the add line link, since yo will be able to add multiple lines.

I 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 values โ€‹โ€‹of the form?

Thanks in advance

+4
source share
2 answers

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

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

closest will be:

Get the first ancestor element that matches the selector, starting with the current element and progressing through the DOM tree.

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

+13
source

To expand the answer to Karim79's question:

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

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

To use the closest () in your situation, you will need to use (there is a bit of busting here):

 $(this).closest("tr").find(".hour").val(); 
+1
source

Source: https://habr.com/ru/post/1315102/


All Articles