What is the best method for adding a header to a dynamically created table using JavaScript?

After receiving JSON data in my JavaScript, I have successfully converted it into an HTML table.

Everything seems to be working fine, but I'm wondering how I can add a header to my table?

Below is the code snippet:

<script>
        $(document).ready(function(){
            $('#id_adv').DataTable();
            $('#id_adv').on('click','.btn',function(){
                var currow = $(this).closest('tr');
                var result = currow.find('td:eq(1)').text();

                $.get('{% url "prop_table" %}', {var1:result}, function (data_prop) {
                    var data = data_prop['data_prop']       
                    var data_json = JSON.parse(data);
                    var html = "";
                    for (var i = 0; i < data_json.length; i++) {
                        html +=  "<tr><td>" + data_json[i].fields.var1 + "</td><td>" + data_json[i].fields.var2 + "</td><tr>";
                        }
                    $('#id_prop').html(html);                      
                })
                document.getElementById('total').innerHTML = result;                    
            });
        });
    </script>

Answer №1

With a slight tweak to your current code, you can easily incorporate a header into your HTML table. By removing the unnecessary use of eval and focusing on the essential part, I have simplified the process for adding the header.

<script>
        ....
                    var html = "";
                    html +=  "<tr><th>Header 1</th><th>Header 2</th><tr>";
                    for (var i = 0; i < data_json.length; i++) {
                        html +=  "<tr><td>" + data_json[i].fields.var1 + "</td><td>" + data_json[i].fields.var2 + "</td><tr>";
                        }
                    $('#id_prop').html(html);                      
        ....
</script>

By following these adjustments, you will successfully add a header to your table. I also echo the sentiments expressed in your question about utilizing the built-in JSON parsing features instead of using vulnerable methods like eval.

Answer №2

In my opinion, it is best practice to add the header after creating the table. By using the createTHead() method, an empty <thead> element is generated and appended to the table. Here's an example:

<script>
    function addTableHeader() {
        var table = document.getElementById("myTable");
        var header = table.createTHead();
        var row = header.insertRow(0);
        var cell = row.insertCell(0);
        cell.innerHTML = "<b>This is a custom table header</b>";
    }
</script>

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

Exploring the functionality of ngTemplateOutlet, the implementation of @ContentChild, and the benefits of using ng

Lately, I've been dedicating more time to grasp the concepts presented in the blog post titled Creating Reusable Components with NgTemplateOutlet in Angular If you want to see the code in action, it's available on stackblitz. Within the UsageEx ...

Is there an equivalent of numpy.random.choice in JavaScript?

The Numpy.random.choice function is a handy tool that allows you to select a sample of integers based on a specific probability distribution: >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array([3, 3, 0]) Is there a similar feature in Java ...

Switching HTML text by clicking or tapping on it

I'm currently working on a website that will showcase lengthy paragraphs containing complicated internal references to other parts of the text. For instance, an excerpt from the original content may read: "...as discussed in paragraph (a) of section ...

UPDATE: Choosing several classes and then toggling the classes independently for each one

I have managed to make this work, but I am considering if there is a more efficient solution. My objective is to modify the divs using classes exclusively. I aim to toggle 4 classes with just one click. First, I obtain the class for the button and then a ...

Can you explain the variance between using 'npm i' and 'npm install'?

Can you explain the distinction between running npm i and npm install? Both commands are used to install all node Modules listed in the package.json file. While the purpose of both commands is clear - to install modules, there may be subtle differences be ...

When using the hasMany/belongsTo relationship in VuexORM, the result may sometimes be

I have carefully followed the documentation and set up 2 models, Author and Book. The relationship between them is such that Author has many Books and Book belongs to an Author. However, despite having the author_id field in the books table, the associatio ...

What is the best way to transfer a variable from a Node.js Express server to an EJS HTML file in order to toggle alert visibility?

Hello, I am currently facing a challenge in sending a variable from my app.js file to my ejs HTML file in order to toggle the display of an alert. Here is what the relevant part of my app.js code looks like: view image description here Initially, I attem ...

How do I access and read a map within an array from Firebase using ReactJS?

I have an array that contains a map with two values: title and content. https://i.stack.imgur.com/WLWVG.png I am trying to read all the values in the array as if it were a map. However, I have attempted this code without success. Can anyone assist me? {d ...

Utilize AngularFire to generate a new User and invoke the factory function to showcase notifications

I recently started working with AngularJS and wanted to integrate it with AngularFire/Firebase for storing project data. I created a factory that manages notifications to be displayed in a centralized location. Here is the structure of my factory: myApp.f ...

My email submission function is malfunctioning

my contact form in my website is not working properly. I have tried troubleshooting the issue by checking the contact.php file but it doesn't seem to be the problem. The script that I am using for the form submission is shown below: <!--Contact U ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...

Implementing a JavaScript function to a button within an existing form in JSP - Best practices

Currently, I am working on developing multiple JSP pages and I encountered a requirement where I needed to add a function to a button within an already existing form. The challenge was that the form's submit button was configured to navigate to anothe ...

Using Ajax to Receive Data in a Separate JavaScript Function

I have a scenario where I am making an AJAX call in one function and attempting to capture the result in another function. Let me explain this in detail below: function myMain(){ var test = myWPackage(); alert(test); } function myWPackage(){ ...

Innovative Mailchimp Ajax Signup Block for Drupal 8

Having trouble ajaxifying the Mailchimp SignUp Block in Drupal 8, specifically with the AjaxResponse. Below is my Form alter hook: function mailchimp_ajax_form_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_sta ...

Why does the old component of the router still receive and handle events when <router-view/> changes?

Ugh... I need to explain a tricky situation I'm facing. I have a parent component that has two children listening for the same event and performing similar actions (see code snippet below): mounted() { EventBus.$on('edit', (data) => { ...

Identifying when a system window covers an iframe

After watching a fascinating YouTube video (https://www.youtube.com/watch?v=TzPq5_kCfow), I became intrigued by how certain features demonstrated in the video could be implemented using JavaScript. One specific question that arose for me was how one can d ...

Replicating JavaScript functions with the power of Ajax

I'm facing an issue with Bootstrap modal windows on my page. The modals are opening and closing successfully, but the content inside them is fetched through AJAX as HTML. For example, there's a button in the modal: <button id="myBtn"> and ...

What is the best way to retrieve the parent of the initial jQuery object?

At the bottom of a lengthy table containing multiple button.enter-match elements, I am using the following code: $("button.enter-match") .button() .on('click', function() { $("form.enter-match").dialog({ modal: true, height: ...

What is the method to receive a JSON response from an HTTPRequest without relying on templates?

I am fairly new to using Django, although I consider myself an experienced programmer in other frameworks. My Goal: To press a form button that triggers Javascript to initiate an Ajax request. This request will be handled by a Django View which will crea ...

Upgrading to Angular 2: Utilizing ElementRef in ES5

Currently, I am facing a challenge in creating an Attribute directive for Angular 2 that would allow me to set multiple default HTML attributes using a single custom attribute. My intention is to apply this directive specifically to the input element. Howe ...