green user green user - 1 month ago 12
Javascript Question

Row in alert box jquery

I have html table i tried to get row data in alert but this show error
when i do this through table row click this is done but i want to do on button click

code

$(function () {
debugger;
$('#table').on('click', 'tr', function () {

debugger;
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
$('#table', 'tr.selected').removeClass('selected');
$(this).addClass('selected');
}

var row = $(this);
debugger;
var value1= row.find('td')[0].firstChild.data;
var value2= row.find('td')[1].firstChild.data;
var value3= row.find('td')[2].firstChild.data;

var s = {};

s.value1= value1;
s.value2= value2;
s.value3= value3;

alert(JSON.stringify(s));

});


$('[ID*=btnadd]').on('click', function () {
var Vechile_ID = '<%=Session["Vechilevalue"]%>';

var value1= $(this).closest("tr").find('td')[0].html();
var value2= $(this).closest("tr").find('td')[1].html();
var value3= $(this).closest("tr").find('td')[2].html();

s = {};
s.value1= value1;
s.value2= value2;
s.value3= value3;

alert(JSON.stringify(s));


});
})


how i do this .. this show an error on this line

var value1= $(this).closest("tr").find('td')[0].html();


Uncaught TypeError: Cannot read property 'html' of undefined(…)

Answer

As you are adding class selected to the tr which has been selected you can use selector $("#table tr.selected") in button click.

Please try with below js :

$(function () {
    debugger;
    $('#table').on('click', 'tr', function () {
        debugger;
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
        }
        else {
            $('#table', 'tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }
    });

    $('[ID*=btnadd]').on('click', function () {
        var Vechile_ID = '<%=Session["Vechilevalue"]%>';

        //Get info of selected tr of table
        var value1= $("#table tr.selected").find('td')[0].html();
        var value2= $("#table tr.selected").find('td')[1].html();
        var value3= $("#table tr.selected").find('td')[2].html();

        s = {};             
        s.value1= value1;
        s.value2= value2;
        s.value3= value3;

        alert(JSON.stringify(s));
    });
});