raptorandy raptorandy - 1 year ago 29
jQuery Question

Getting the name of an input inside the last row

This is the base of a table that I have.
It could have many more rows and the last number in the name attribute indicates the row number. I want get the name attribute of any of the inputs inside the last row. It does not matter which input is because then I will split the string and only keep the last number.

How can I achieve this?
Thanks!

<table id="tableNames">
<tbody>
<tr>
<td>
<input type="text" name="contact1_1"/>
<input type="text" name="contact2_1"/>
<input type="text" name="contact3_1"/>
</td>
<td>
<input type="text" name="phone1_1"/>
<input type="text" name="phone2_1"/>
<input type="text" name="phone3_1"/>
</td>
</tr>
</tbody>
</table>

Answer Source

:last selector with split() and pop()

console.log( $("#tableNames tbody tr:last input:last").attr("name").split("_").pop())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableNames">
    <tbody>
        <tr>
            <td>
                <input type="text" name="contact1_1"/>
                <input type="text" name="contact2_1"/>
                <input type="text" name="contact3_1"/>
            </td>
            <td>
                <input type="text" name="phone1_1"/>
                <input type="text" name="phone2_1"/>
                <input type="text" name="phone3_1"/>
            </td>
        </tr>
    </tbody>
</table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download