raptorandy
raptorandy

Reputation: 225

Find the value of first input in last table row by class

How can I get the value in the first input of the last row of a table using the class name?

The table can have many rows and in every one of them there is an input in the first column with the class "inputtext'.

I thought something like this could work but it does not.

$("#tableData tr:last input[class=inputtext]").val();

Upvotes: 0

Views: 3168

Answers (4)

NtFreX
NtFreX

Reputation: 11377

How can I get the value in the first input of the last row of a table using the class name

The = operator you used in your css selector only matches an element when the value is exactly the same as the one you searched for.

You can use the *= operator instead which will match an element when it contains the searched value.

console.log($("#tableData tr:last input[class*=inputtext]").val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableData" class="table table-hover">
    <tbody>
        <tr>
            <td>
                ... 
            </td>
            <td>
                ...
            </td>
            <td>
                ...
            </td>
        </tr>
        <tr>
            <td><input type="text" class="form-control inputtext" value="1234"/> </td>
            <td><input type="text" class="form-control inputtext" value="4321"/> </td>
        </tr>

    </tbody>
</table>

Upvotes: 1

charlietfl
charlietfl

Reputation: 171698

I want to get the value of the first input in the last row

Use :last on row and :first on input

$("#tableData tr:last input:first").val();

Upvotes: 1

gaganshera
gaganshera

Reputation: 2639

Since your input element has 2 classes, the input[class=inputtext] wont work.
Do it like this: $("#tableData tr:last input.inputtext").val().
input.inputtext will search for input having atleast one class namely inputtext.

console.log($("#tableData tr:last input.inputtext").val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableData" class="table table-hover">
    <tbody>
        <tr>
            <td>
                <input type="text" name="input_1" id="input_1" class="form-control inputtext"/> 
            </td>
            <td>
                ...
            </td>
            <td>
                ...
            </td>
        </tr>
        <tr>
            <td><input type="text" name="input_1" id="input_1" class="form-control inputtext" value="3234"/> </td>
        </tr>

    </tbody>
</table>

Upvotes: 2

Osama
Osama

Reputation: 3030

The input field is in the first row as your HTML show and you use last so it is not true here it will work with you

$("#tableData tr:first input[class=inputtext]").val();

Upvotes: 0

Related Questions