Scelo
Scelo

Reputation: 45

How to get values from an html table column <td> of a selected row <tr> using javascript

i have an html table that is displayed on my web application, but i would like to select a row by clicking on it and then have a button to get each columns data as variables i can use in javascript. this is what i was trying but it's not complete because i do not know what to do. remember i want what's in the columns. my function...

function selectedRows() 
{
   var selectedItems = ('#ScannedLabelTabl; // i wanted to get the selected item (row)

     $.each(selectedItems, function (i, item) {


      });

}

Upvotes: 0

Views: 6290

Answers (5)

Bachas
Bachas

Reputation: 243

var tableRows = $("#ScannedLabelTabl").find("tr");//fetching all rows of the tblebody
$.each(tableRows, function( index, value ) {//iterating all fetched rows
     var tdValue=$(value).find("td:nth-child(3)").html();   
     (value).find("td:nth-child(3)").addClass("adding");//get particular column

Upvotes: 0

user2063626
user2063626

Reputation:

Try below code

  $(function () {

    $("td").click(function () {
        $("td", $(this).parent()).each(function () {
            alert($(this).html());
        })
    })

Upvotes: 0

Hugo Alves
Hugo Alves

Reputation: 1555

assuming you want to allow multiple selections (not sure if that's what you want) you may add a click event handler to the cells that do

$("tr").click(eventHandler);

function eventHandler(){
    //what this does is verifies of the element has the class, if it doesn't have the class is addeds, if it has the class it's removed
    $(this).toggleClass("selected");
}

then to get all the values do something like this:

function getAllValues(){
    var arrayOfValues = [];
    $(".selected").each(function(){
        var value = $(this).//what you want to get val or text
        arrayOfValues.push()

    });
    return arrayOfValues;
}

Upvotes: 0

turiyag
turiyag

Reputation: 2887

The easiest way I could think of doing this would be to add a class to the row/column when the user clicks the element. CSS styles could apply, and jQuery's class selector could be used to enumerate the selected elements.

I'll build a JSFiddle.

Aww. Too slow. Props to Ovilia.

Upvotes: 0

Ovilia
Ovilia

Reputation: 7256

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

    var td = $(this).children('td');
    for (var i = 0; i < td.length; ++i) {
        alert(i + ': ' + td[i].innerText);
    }
});

Run demo here: http://jsfiddle.net/VjkML/

Upvotes: 1

Related Questions