[Solved] JavaScript and jQuery Alert find(“td:first”).html() and Click


It’s really unclear what the goal is here. Maybe this will help, consider the following code.

$(function() {
  function cereal(id, name, like) {
    this.id = id;
    this.name = name;
    this.like = like;
  }

  const cereals = [
    new cereal(1, 'Captain Crunch', 'Yes'),
    new cereal(2, 'Frosted Wheats ', 'Yes'),
    new cereal(3, 'Shredded Wheat', 'No'),
    new cereal(4, 'Trix', 'No'),
    new cereal(5, 'Count Chocula', 'No'),
  ];

  var output = "<h1>Cereal Listing</h1>";
  output += "<table class="cereal-table"><thead>";
  output += "<tr><th>Id</th><th>Cereal Name</th><th>Like?</th></tr>";
  output += "</thead><tbody>";
  $.each(cereals, function(k, c) {
    var row = $("<tr>", {
      "data-c-id": k
    });
    $("<td>").html(c.id).appendTo(row);
    $("<td>").html(c.name).appendTo(row);
    $("<td>").html(c.like).appendTo(row);
    output += row.prop("outerHTML");
  });
  output += "</tbody></table>";

  $("#cer").html(output);
  $(".cereal-table").on("click", "tr", function(e) {
    var cId = parseInt($(this).data("c-id"));
    console.log("Row C-ID: " + cId);
    var data = "";
    data += "ID: " + cereals[cId].id;
    data += ", Name: " + cereals[cId].name;
    data += ", Like: " + cereals[cId].like
    alert(data);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="cer"></div>

Since jQuery is a JavaScript Framework, you can mix and match both, yet I try to remain in one or the other. This is all in jQuery.

The function creates an Object. You have 5 objects in an Array and we’re going to iterate the Array using $.each(). This is a functioned designed for this. See:
jQuery.each()

Each Object has parameters we can call and insert into the Table Cell elements <td>. jQuery give us the ability to quickly create elements as jQuery Objects: $("<td>").

Since the goal appears to be to create an output string of HTML text, we can convert all the jQuery Objects we’ve create into HTML by asking for the outerHTML property.

The result of running the code is:

<h1>Cereal Listing</h1><table><thead><tr><th>Id</th><th>Cereal Name</th><th>Like?</th></tr></thead><tbody><tr><td>1</td><td>Captain Crunch</td><td>Yes</td></tr><tr><td>2</td><td>Frosted Wheats </td><td>Yes</td></tr><tr><td>3</td><td>Shredded Wheat</td><td>No</td></tr><tr><td>4</td><td>Trix</td><td>No</td></tr><tr><td>5</td><td>Count Chocula</td><td>No</td></tr></tbody></table>

Once the table is constructed and outputted, you can bind a click event to the Row with .on() or .click(). I advise the .on() since it more tolerate of dynamic content.

We bind the click event to each row and then collect the data from the row and create an alert.

Hope this helps.

4

solved JavaScript and jQuery Alert find(“td:first”).html() and Click