Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67411

Identify which td element was click if none of the td have ids

$
0
0

I am trying to update a <div> with a table using jQuery. I want to add a click handler to each <td>, but the click handler will be different for each <td>. How do you tell which <td> was clicked if it doenst have a id?

$(document).ready(function(){
  $("button").click(function(){

    $.post("controller.php",{ },
    function(data){
      var obj = JSON.parse(data);
      var object;             

      //add to a table...
      var t = "<table id='newstable' class='table table-dark table-hover'><thead><tr><th>Post Subject</th><th>Last Post</th></tr></thead><tbody>";
      for (var i = 0; i < obj.length; i++) {  // for each row
        object = obj[i];
        t += "<tr>";                        
        t += "<td colspan='2'>" + object[Object.keys(object)[0]] + "</td>";  // the property value, not the property name 
        //future lastpost td
        t += '</tr>';
      }
      t += '</tbody></table>';
      alert(t);

      $("#main-container").html(t);
    });
  });
});

I understand that in order to get the id you must use this code

$(document).ready(function() {
    $("#mycontainer").on('click', '#newtable tbody tr td', function(event) {
        alert(event.target.id);
    });
});

but what if the id wasn't set?

Anyone have any recommendations? or guidance? Thanks

I tried to code Daniel Lizik advice and here is what I came up with. It doesnt work. Any ideas how to fix it would be greatly appreciated. thanks.

$(document).ready(function(){
        $("#main-container").on('click','#newstable tbody tr td',function(event){       
            var clickedTd = event.target;       
            var newsTd;

                $("#newstable td").each( function(){
                    newsTd = $(this);                   
                    if(clickedTd == newsTd){
                        alert("they match");
                    } else {
                        alert("no match");
                    }
                });         

        });
});

Viewing all articles
Browse latest Browse all 67411

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>