Kelsey Kelsey - 6 months ago 12
jQuery Question

How to get ID of 3rd Previous Input Type Time Once Button is Clicked

I have got the following inputs like so:

<tr><td><input type='time' id='32'></td><td><input type='text'></td></tr>
<tr><td><input type='time'></td><td><input type='time' ></td><td><button class='clicker'>Get ID</button></td></tr>


When I click the button I want Jquery or JS to alert me the ID in the 3rd previous input (where type=time), which is "32".

I have tried the following code:

alert($(this).prev('input[type=time]').prev('input[type=time]').prev('input[type=time]').attr('id'));


However, I keep getting "undefined".

Any ideas?

Answer

You can do it like following.

$('.clicker').click(function() {
    alert($(this)
        .closest('tr')
        .prev('tr')
        .find('input[type=time]').attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td><input type='time' id='32'></td>
        <td><input type='text'></td>
    </tr>
    <tr>
        <td><input type='time'></td>
        <td><input type='time'></td>
        <td><button class='clicker'>Get ID</button></td>
    </tr>
</table>