Having trouble triggering the onclick event on a dynamically created table using JavaScript

I am facing an issue with adding a table programmatically that has an onclick event triggering a specific JavaScript function using the row's id for editing purposes. Unfortunately, the function is not being called as expected. I have attempted to modify the button by adding a class and tweaking some code, but it appears to be unsuccessful. This functionality was previously working fine, and now I am struggling to identify the cause and solution.

function buildTable() {
$.ajax({
    url: "getTable.php",
    dataType: "json",
    success: function(result) {
        if (result != null) {
            $('#measurements tbody tr').remove();
            result.forEach(function (measurement) {
                var message = "<tr><td>" + dateFromtimestamp(measurement.weigh_date) + "</td>";
                ...
                // Code continues here, creating HTML elements dynamically
            });
        }
    }
});

}

The table structure in question:

<div class="panel panel-info">
<div class="panel-heading text-center">Past measurements</div>
<div class="panel-body">
    <table class="table table-striped" id="measurements">
        <thead class="thead-dark">
        ...
         // Table columns continue here
     </table>
     <div class="row">&nbsp;</div>
 </div>
 </div>

The edit function causing trouble:

function editRow(id) {
    $.ajax({
       ...
       // Edit function details go here
    });
}

I also tried changing the button markup by adding a class: and attempted to capture the click event using $('.editRow').on("click", function() {} method with no success.

Answer №1

There is a small error in your code with onlick, it should be onclick.

Additionally, you might want to consider using passive event listeners like this:

$(document).on("click", <target>, <your function>});

Replace <target> with the jQuery selector for your button, and <your function> with your callback function.

This approach can improve readability and maintain a clear separation between HTML and JavaScript. It also works well for dynamically added elements.

Answer №2

Shout out to kmgt for the assistance! It was right under my nose, I just had to use 'onclick' instead of 'onlick'.

Answer №3

Firstly, I agree with @dmitrii-g's suggestion to utilize event delegation in order to effectively handle any events on elements that were added dynamically after the DOM has been rendered. Additionally, it is important to debug or print necessary information to the console to ensure that correct values are being passed into your function. To illustrate this approach, I have provided a sample example:

const result = [{
  weigh_date: '01/01/2019',
  weight: '200lbs',
  id: 1,
  waist: 'waist',
  upperBp: 'upperBp',
  lowerBp: 'lowerBp',
  comment: 'comment'
},
{
  weigh_date: '01/01/2015',
  weight: '100lbs',
  id: 2,
  waist: 'waist',
  upperBp: 'upperBp',
  lowerBp: 'lowerBp',
  comment: 'comment'
}
];

function buildTable() {
if (result != null) {
  $('#measurements tbody tr').remove();
  result.forEach(function(measurement) {
    var message = "<tr><td>" + measurement.weigh_date + "</td>";
    message += "<td>" + measurement.weight + "</td>";
    message += "<td><input type='hidden' value='" + measurement.id + "'>" + measurement.waist + "</td>";
    message += "<td>" + measurement.upperBp + "</td>";
    message += "<td>" + measurement.lowerBp + "</td>";
    message += "<td>" + measurement.comment + "</td>";
    message += "<td><button type='button' class='btn btn-edit btn-outline-warning' id='" + measurement.id + "'>Edit</button> ";
    message += "<button type='button' class='btn btn-delete btn-outline-danger' id='" + measurement.id + "'>Remove</button></td></tr>";
    $('#measurements').append(message);
  });
}
}

$('#measurements').on('click', '.btn-edit', function() {
const id = $(this).attr('id');

console.log('ID to be edited: ' + id);
// additional actions can go here
});


$('#measurements').on('click', '.btn-delete', function() {
const id = $(this).attr('id');

console.log('ID to be deleted: ' + id);
// additional actions can go here
});


buildTable();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-info">
  <div class="panel-heading text-center">Past measurements</div>
  <div class="panel-body">
    <table class="table table-striped" id="measurements">
      <thead class="thead-dark">
        <th scope="col">Date</th>
        <th scope="col">Weight</th>
        <th scope="col">Waist</th>
        <th scope="col">Systolic (Upper)</th>
        <th scope="col">Diastolic (Lower)</th>
        <th scope="col">Comment</th>
        <th scope="col">Action</th>
      </thead>
      <tbody>
      </tbody>
    </table>
    <div class="row"> </div>
  </div>
</div>

Answer №4

check this out

$(document).on("click","tr",function() {
    console.log(this,"clicked");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming jQuery Object into a String after making an AJAX request

If I were to submit a form with some text in the value of user_input, let's say "I am free," through AJAX, and it comes back to me as a string. Once it becomes an Object, how could I convert it back into a string format? Thanks, <!DOCTYPE HTML> ...

The Socket IO Client is receiving a different object than the one that was sent by the Server

My server side code is sending an object to the client side, but the object received by the client is completely different from what was sent. Let me elaborate: Code Server side code: //Setting up the example var response={}; response.models=[]; respo ...

Using XMLHttpRequest with gzip compression

Utilizing the request module in node.js makes it simple to create a request that can retrieve and correctly decompress compressed data from the source: var request = require('request'); var requestOptions = { url: 'http://whatever.com/g ...

Alignment problem detected in Firefox and Safari, but works perfectly in Chrome

Currently dealing with a CSS problem on my website that is only appearing in Safari and Firefox, while Chrome displays it correctly. The images are not positioning correctly and are stacking instead of being placed in each box as intended. I've expe ...

React Select only enabling single selection at a time

Currently, I am in the process of updating my react app to version 16.8 and also updating all associated libraries. One issue that has come up is with two drop-down selects from Material UI. Since the update, the multi-select option no longer allows multip ...

Show a PDF document on the webpage by making an ajax request in a C# MVC application

Using ItextSharp, I am creating a Pdf from html and trying to show a preview of the Pdf on the screen for the user to interact with. Although the Pdf generation is correct, I am struggling to display it on the screen. Here is the Ajax call: function Pre ...

The menu does not adjust to fit the site properly, causing the video/photos to appear off to the right on smaller screens

Earlier, I received some fantastic help for which I am extremely grateful. However, I find myself in need of your expert assistance once again. The website I am currently working on is . After simplifying the code and removing absolute positioning, I enco ...

When Socket.emit is called, it outputs <span> elements within a well-structured message

Currently working on a small chat application using Node.js, Express.js, and Socket.IO. However, I'm encountering an issue with formatting. Instead of displaying the message content within <span> tags as intended, it is printing out the actual t ...

Utilizing Regular Expressions in JavaScript to extract packages from an Android manifest document

When it comes to Android APK files, the manifest files play a crucial role: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp" android:versionCode="1" ...

Having Trouble Styling Radio Buttons with CSS

Hello, I'm facing an issue with hiding the radio button and replacing it with an image. I was successful in doing this for one set of radio buttons, but the second set in another row is not working properly. Additionally, when a radio button from the ...

How can one ensure that Discord waits for a script to complete running, and how can you prevent Discord from responding until all necessary data has been obtained?

I recently started working with node.js and asynchronous programming, and I'm facing a challenge that has me puzzled. My goal is to create a Discord bot that fetches data from a third-party website. While I can successfully retrieve the data and see i ...

Receiving HTML from NodeJs instead of JSON

I am currently working on a project that involves developing an app and landing pages. While we are using NodeJs with Axios and VueJs for the app part, the landing pages are built using simple jQuery. I need to make API calls for the landing pages, but I a ...

Grabbing a section of a URL through a bookmarklet: A simple guide

Recently, I've been using this handy bookmarklet: javascript:currentUrl=document.location.href;document.location.assign(currentUrl+'embed'); This neat tool grabs the current URL, such as www.example.com/knZg_INW8fL/, and adds embed to it f ...

Creating an ongoing loop endlessly using recursion in node.js

Seeking assistance in creating a recursive loop to continuously iterate through functions in Node.js for flow control. I have tried online tutorials but still struggling to comprehend it fully. Can anyone provide guidance or point me towards a proper tutor ...

Error: Attempted the use of 'append' method on an object lacking the implementation of FormData interface, with both processData and contentType set to false

Apologies for any English errors. I am attempting to use ajax to submit a form, and here is my JavaScript code: $("#formPublicidad").on('submit', function(event) { event.preventDefault(); var dataForm = new FormData(document.getElementBy ...

How do the scopes of a controller and a directive's controller differ from each other?

Can you explain the difference between a controller and a directive's controller in terms of scope? I'm struggling to grasp the distinction and whether it's necessary to create controllers within the DDO for my directives. In the code snipp ...

Guide to dynamically updating text using Jquery

Is there a way to dynamically change text? I want the ability to double-click on text, have it appear in an input field, then clear and rewrite it. Take a look at my initial code snippet Jsfiddle <div id="main_text"> <h1>Change Text</h ...

Using setAttribute will convert the attribute name to lowercase

When creating elements, I use the following code: var l = document.createElement("label");. I then assign attributes with l.setAttribute("formControlName","e");. However, a problem arises where the setAttribute method converts formControlName to lowercase ...

What is the best way to change a JavaScript variable into a PHP variable?

I am interested in converting my JavaScript variable to a PHP variable... Currently, I have the following scenario - in the code below there is a variable e, but I would like to utilize e in PHP as $e: <script> function test() { var e = documen ...

What is the best way to switch the site header in JavaScript or jQuery?

I have created a Bootstrap menu design and I am looking to add a sliding functionality to it. My goal is to hide the menu when scrolling down and display it when scrolling up (slide-down / slide-up). For implementing this feature, I plan to utilize jQuery ...