1

Now I have a table that generate by using javascript .Below is my code to generate table :

$.ajax({
            type:"POST",
            url:"../cdc/load/jsonTrack.php?",
            data:dataString,
            dataType: 'json',
            success: function(data){
                if(data.status === "success") { 
                    var elements = data.elements; 
                    if(elements.length === 0) {
                        $('#cdcTracking-list tbody').append( '<tr>' +
                            '<td colspan="7">No session to display</td>' +
                            '</tr>');
                    }
                    for( var i = 0; i < elements.length; i++){
                        var element = elements[i];

                        //console.log('session id:' + element.vesselCode);
                        $('#cdcTracking-list tbody').append( '<tr>' +
                            '<td style="color: green;">' + element.vesselCode + '</td>' +
                            '<td style="color: black;">' + element.voyage + '</td>' +
                            '<td style="color: black;">' + element.chasisNo + '</td>' +
                            '<td style="color: black;">' + element.chasisNo + '</td>' +
                            '<td style="color: blue;">' + element.plateNo + '</td>' +
                            '<td style="color: blue;">' + element.bookingRef + '</td>' + 
                            '<td style="color: blue;">' + element.serviceTerm +'</td>'+
                            '</tr>'                                    
                        );
                    }
                }else { 
                    $('#cdcTracking-list tbody').append( '<tr><td colspan="7">No session to display</td></tr>');
                }
            }
        }); 

Does anyone know how can I get some column data and it header by onclick ,because my current code seem not working and I dont know if I'm missing something here.Below is my code to get :

$('#cdcTracking-list tr td').click(function() {

        var header = $('#cdcTracking-list th').eq($(this).index()).text(); //to get clicked column's header
        var trackid = $(this).siblings('td:nth-child(36)').text(); //get column at column 36
        var date = $(this).text(); //get clicked column value
});

Does anyone have a experience with this ,and please help me out

2 Answers 2

2

You need to use delegation. because when dom is loaded there is no table data like this. Table is created after the DOM load by an ajax call.

$(document).on("click", "#cdcTracking-list tr td", function() {
    var header = $('#cdcTracking-list th').eq($(this).index()).text(); //to get clicked column's header
        var trackid = $(this).siblings('td:nth-child(36)').text(); //get column at column 36
        var date = $(this).text(); //get clicked column value
});

You can also target ancestor(#cdcTracking-list) instead of document if it was from the initial load of DOM like given below.

$('#cdcTracking-list').on("click","tr td",function(){
//code
}); 
Sign up to request clarification or add additional context in comments.

1 Comment

There is still a lot of repeated code with this answer. Why not DRY it up and then attach the click event to the newly created object at time of creation instead of re-querying / filtering after the fact?
0

Attach the click event to the element as you create them:

$('<td>').on('click', doClick);

Here is a cleaned up and commented version to illustrate:

// This is used a lot, we should keep a reference for cleaner code.
var $table = $('#cdcTracking-list tbody');

// No need to repeat the same pattern of code so we will use JS to iterate over
// code by telling it the values we want in each iteration. This is used for the
// makeElementTR helper function.
var dataKeys = [
  {prop: 'vesselCode',  color: 'green'},
  {prop: 'voyage',      color: 'black'},
  {prop: 'chasisNo',    color: 'black'},
  {prop: 'chasisNo',    color: 'black'}, // This is repeated, Why?
  {prop: 'plateNo',     color: 'blue'},
  {prop: 'bookingRef',  color: 'blue'},
  {prop: 'serviceTerm', color: 'blue'}
];

function onElementClick(e) {
  var header  = $('#cdcTracking-list th').eq($(this).index()).text(); //to get clicked column's header
  var trackid = $(this).siblings('td:nth-child(36)').text(); //get column at column 36
  var date    = $(this).text(); //get clicked column value
  // Do something with this?
}

// Making helper functions can make code further down easier to understand
function makeElementTR(element) {
  var $tr = $('<tr>');
  $.each(dataKeys, function(index, dataKey) {
    var value = element[dataKey.prop];
    $('<td>')
    .on('click', onElementClick)
    .css({color: dataKey.color})
    .text(value)
    .appendTo($tr);
  });
  return $tr;
}

$.ajax({
  type: 'POST',
  url: '../cdc/load/jsonTrack.php',
  // I hope this is not a normal string. That would be weired.
  data: dataString,
  // How come your PHP script can't set the 'Content-Type: application/json'?
  // If it did you wouldn't need this.
  dataType: 'json'
})

// Using success callbacks, especially when defined in-line, is really hard to
// read. Use jQuery's promise-like syntax for more readability and flexibility.
.then(function(data) {
  var elements = data.elements;

  // Don't repeat yourself, If your going to respond the same with either
  // success !=== 'success' or no elements put them both in the same if
  // statement.
  if (data.success !== 'success' || elements.length === 0) {

    // Wait a second, if the code reaches here then that means the PHP script
    // returned a 200 (Success/Happy) response except the data.success is
    // telling the you the server lied? It would be easier to have the PHP
    // script return an error response instead of a success response here.
    // However, if that isn't possible then we will fake that is what happened
    // by throwing our own exception which will be passed on as if the server
    // said as much.
    throw "No session to display"; // Let someone else handle this.
  }

  $.each(elements, function(index, element) {
    makeElementTR(element)
    .appendTo($table);
  });
})

// This guy knows what to do when things are not working the way we want.
.fail(function(reason) {
  if (typeof reason === 'string') {
    $('<tr>')
    .append($('<td>', {colspan: 7}).text(reason))
    .appendTo($table);
  } else {
    alert('Oh no! Something bad happend: ' + reason); // coherce to string
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.