Jquery - get input field value from last row of table?

I'm a little confused about how to do this ...

I have a table that has a row of rows, and inside each cell there are certain form elements. I am trying to get the value from the "code" input field only from the last line, and I am having problems with the syntax ...

A simplified table looks like this:

<table id="table1">
<tr><td><input type="hidden" name="code" value="XFT" /></td></tr>
<tr><td><input type="hidden" name="code" value="ETY" /></td></tr>
<tr><td><input type="hidden" name="code" value="DHQ" /></td></tr>
</table>

And here's a jquery that doesn't work ...

if($('#cont')) {
            $("#cont').live('click', function(event) {
                var tr = $('#wr-viewcarttable tr:last');
                var itemcode = $(tr > 'input[name="code"]').val();
                window.location = "/search?p="+itemcode;
            });
        }
+5
source share
1 answer

Try the following:

$('table#table1 tr:last input[name=code]').val();

Or, adjusted to your code:

$('#cont').live('click', function(event) {
    var tr = $('#wr-viewcarttable tr:last');
    var itemcode = tr.find('input[name=code]').val();
    window.location = "/search?p="+itemcode;
});

You have two errors in the code, you have inappropriate quotation marks in part $("#cont'), and your input search is incorrect. Now you have:

$(tr > 'input[name="code"]').val();

> , , , tr 'input[name="code"]'. (true false), :

$(true).val();

. jQuery, find , , $(). , :

tr.find('input[name=code]').val();
$('input[name=code]', tr).val();

tr , , .

+11

All Articles