Mark Moonie Griffiths Mark Moonie Griffiths - 7 months ago 10
HTML Question

Selecting a row in a html table

I am trying to select a row in a table I have created and need use the values. The issue I am having is I created it using doms in javascript and got the values from a stored procedure which then populates the table.

so i use a simple div with an id -

<div id="Tab1" class="tab-pane fade in active"></div>


to create the table and populate it i use an ajax call -

function GetcarData() {

$.ajax({
type: "post",
data: JSON.stringify({
price: slidval,
}),
url: "/index.aspx/GetData",
dataType: "json",
contentType: "application/json",
success: function (object) {
responseData(object);
},
complete: function (object) {

},
error: function (object) {
}
});
}
function responseData(object) {
var stringed = JSON.stringify(object.d)
var arr = JSON.parse(stringed);
var i;
var out = "<table id='table' class='table table-striped'>";
var rowHeader = $("<tr></tr>").appendTo(out);
out += "<td><font size='4'>Make</font></td>";
out += "<td><font size='4'>Model</font></td>";
out += "<td><font size='4'>Version</font></td>";
out += "<td><font size='4'>Engine</font></td>";
out += "<td><font size='4'>(AV)Price new</font></td>";
out += "<td><font size='4'>(Av)Price used</font></td>";
out += "<td><font size='4'>Image</font></td>"

for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Make +
"</td><td>" +
arr[i].Model +
"</td><td>" +
"£" + arr[i].version +
"</td><td>"+
arr[i].Engine_size +
"</td><td>" +
"£" + arr[i].price_new +
"</td><td>" +
"£" + arr[i].price_used +
"</td><td><img src="+arr[i].image_url+" width='150' height='100'>" +
"</td></tr>";
}
out += "</table>";
document.getElementById("Tab1").innerHTML = out;

}


Now the issue I have is I cant seem to select a row.
I tried

("#table tr").click(function(){
alert("selected");
});


but that did not work.

Anyhelp would be appreciated

Answer

You created a set of elements that weren't in the DOM when page and were only added after initial DOMContentLoaded

To listen for events on elements that are dynamically added, removed via JavaScript DOM manipulations, you need to use slightly different event listener.

$(document).on('%eventName%', '%selector%', function() { // do your stuff });