Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find selected row using jquery

I have a table and a button to get the selected row:

<table id="mytable" class="table-striped">
    <tbody>
        <tr id="1"><td>Test1</td></tr>
        <tr id="2"><td>Test2</td></tr>
        <tr id="3"><td>Test3</td></tr>
        <tr id="4"><td>Test4</td></tr>
        <tr id="5"><td>Test5</td></tr>
    </tbody>
</table>
<button id="btn">Get Selected Row</button>

When I clicked the row I set the background color into red.

$('#mytable').on('click', 'tbody tr', function (event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});

function getRow() {
    $('table > tbody > tr').find('background-color: red');
}

$('#btn').click(function (e) {
    var selrow = getRow();
    console.log(selrow);
    if (selrow != undefined)
        alert(selrow.attr('id'));
    else
        alert('undefined');
});

The question is how to get the selected row (where background color is red) using jquery, when I clicked the button?

Here is what I've done: http://jsfiddle.net/xu2AH/865/

like image 642
Willy Avatar asked Oct 16 '25 16:10

Willy


1 Answers

You can match any rows that have the .highlight class with tr.highlight.

If you want the jQuery object (if a match is found) you'll need to return it within your getRow() function:

function getRow() {
    return $('table > tbody > tr.highlight');
}

JSFiddle

like image 174
George Avatar answered Oct 18 '25 09:10

George