Mark Moonie Griffiths Mark Moonie Griffiths - 2 years ago 76
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() {

type: "post",
data: JSON.stringify({
price: slidval,
url: "/index.aspx/GetData",
dataType: "json",
contentType: "application/json",
success: function (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 +
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'>" +
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(){

but that did not work.

Anyhelp would be appreciated

Answer Source

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 });

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download