user3221714
user3221714

Reputation: 41

How to get selected row from a table in html using javascript?

I have a html table and a button below it, I want to get the data from the selected row whenever that button is clicked. How shall I go about it?

Upvotes: 0

Views: 8750

Answers (1)

user3886234
user3886234

Reputation:

If I understand what you mean, you want a user to be able to select a row out of a table by clicking on it. Then when they click the button, you can capture the selected row's data in each cell.

I'll use JQuery in the explanation.

You will want to create an event handler for a click event on a <tr>. When that <tr> is clicked, you can apply a CSS class such as .selected to it. Then when the user clicks the button, you have another event handler loop through the .selected class's children and return the values (which would be <td>'s).

$('tr').click(function() {
   $('.selected').removeClass('selected');
    $(this).addClass('selected');
});

$('#submit').click(function() {    
    $('.selected').children().each(function() {
        alert($(this).html());
    });
});

Here is a working example on JSFiddle using JQuery.

Upvotes: 2

Related Questions