Generating an interactive button click feature within a cell of a data table

Can someone help me figure out why I am getting a SyntaxError when trying to trigger a function in a datatable cell using an onclick event on a button? The button is successfully created, but the error occurs when clicking it.

The problem seems to lie within the render switch case 0. The exact error message I'm receiving is:

SyntaxError: expected expression, got '}'

Here is the code I am using:

function LoadHistory(phone) {
    $.ajax({
        url: '/api/TransferFunds/' + phone,
        type: 'Get',
        dataType: 'json',
        contentType: "application/json; charset-utf-8",
        success: function (data) {
            datatableVariable = $('#table').DataTable({
                data: data,
                autoWidth: true,
                responsive: false,
                paging: true,
                lengthChange: false,
                searching: false,
                ordering: false,
                info: true,
                columns: [
                    { 'data': 'id' },
                    { 'data': 'transType' },
                    { 'data': 'network' },
                    { 'data': 'phoneNumber' },
                    { 'data': 'internalReference' },
                    {
                        'data': 'amount',
                        "render": function (value) {
                            return "GHS" + formatmoney(value);
                        }
                    },
                    {
                        'data': 'dateSent',
                        "render": function (value) {
                            return value;
                        }
                    },
                    {
                        'data': 'status',
                        "render": function (data, type, row, meta) {
                            var evt = row['internalReference'];
                            switch (data) {
                                case 0:
                                    return '<button class="btn btn-default" onclick="return GetStatus("' + evt + '");">Pending&nbsp;&nbsp;&nbsp;</button>';
                                    break;
                                case 1:
                                    return '<button class="btn btn-success" >Successful</button>';
                                    break;
                                case 2:
                                    return '<div class="btn btn-warning">Rejected&nbsp;&nbsp;</div>';
                                    break;
                                case 3:
                                    return '<div class="btn btn-danger">Failed&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>';
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                ],
                columnDefs: [
                    { "visible": false, "targets": [0, 4] }                    
                ]
            });
            
        }
    });
}

Answer №1

One suggestion is to utilize template literals to easily inject values into a string.

return `<button class='btn btn-default' onclick='GetStatus("${evt}")'>Pending&nbsp;&nbsp;&nbsp;</button>`

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

Steps to reveal a div when a button is clicked within a v-for loop using VueJS

Context In my code, I am utilizing a v-for loop to display sets of buttons and corresponding input fields. Each button is supposed to trigger the display of its respective input field upon being clicked. Issue However, the problem arises when the button ...

Using React to sort and retrieve only the duplicate values in an array

Within this Array, I am retrieving all the idCategory values of "answersTo", some of which are duplicates. I'm trying to filter out only those duplicates, but it's not a straightforward comparison since there is no specific data to compare agains ...

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

How to simulate keyboard events when a dropdown list is opened in an Angular application

Requirement- A situation arises where upon opening the dropdown menu, pressing the delete key on the keyboard should reset the index to -1. Steps to reproduce the issue: 1. Click on the dropdown and select an option from the menu. 2. Click on the dropdow ...

What is the best way to format a date input field so that when a user enters a year (yyyy), a hyphen (-

Need help with date formatting in the format yyyy-mm-dd. Seeking a way to prompt user input for the year and automatically append "-" to the date as needed. Also utilizing a datepicker tool for selecting dates. ...

Is the User Session different in JQuery AJAX compared to a postback on the same website?

Is there a difference in User Session between JQuery AJAX and a postback on the same website? I am attempting to pass data to an MVC2 Controller using a Jquery Ajax POST with a query string, then have the Controller extract the data from the query string ...

retrieve particular content from html following ajax return

Currently, I am in the process of working on ajax functionality where I need to send a request to retrieve data from a specific page. The challenge that I am facing is that the target page contains a complete template with a header, footer, side menu, and ...

The code generated by Asto SSR may not be compatible with older iOS versions, causing it to fail to run

I have been running my astro SSR site on Netlify with great success. However, I recently encountered an issue when testing it on older iPhone models like the iPhone 6 and earlier. It seems that all script executions halt, rendering the site non-interactive ...

Creating a project that utilizes Bing Translate and the Node.js programming language

As I work on developing a web application that enables users to translate text using the Bing translator API, I am facing an issue. I attempted to execute a translator.js file via a script tag, but encountered a roadblock since Node.js code cannot be run t ...

Swapping out nodes for images using d3.js

Below is the code snippet I am currently executing http://jsfiddle.net/a7as6/14/ I have implemented the following code to convert a node to an image: node.append("svg:image") .attr("class", "circle") .attr("xlink:href", "https://github.com/favico ...

Endless loop JSON vulnerability

I recently came across a discussion on Stack Overflow about Google's practice of prepending while(1); to their JSON responses. Can anyone provide guidance on what type of PHP script would be suitable for this situation? I attempted the following: $ ...

Try utilizing a variety of background hues for uib progressbars

Looking to incorporate the ui-bootstrap progressbar into my template in two different colors, background included. My initial idea was to stack two progress bars on top of each other, but it ended up looking too obvious and messy, especially in the corner ...

The process of generating an efficient build gets stuck and never finishes

I am currently facing an issue while attempting to build my React app. Whenever I execute "npm run build," the terminal gets stuck at "Creating and optimized production build..." and doesn't complete the process. I have tried running this on a system ...

AngularJS: Controller isn't being triggered

I'm encountering a peculiar issue with AngularJS where MainCtrl is not functioning at all. When I visit localhost/, it automatically redirects to localhost/#/ but the page remains blank. There are no error messages in the console, and I can confirm th ...

When using XML, what situations can cause jquery's .attr() and getAttribute() to provide varying results?

When I receive an XML response from a server and parse it in jquery (jQuery 1.8.2 on Chrome 23.0.1271.64 and Firefox 15.01) to retrieve various attributes, it works correctly most of the time. However, occasionally the attr() call returns the entire elemen ...

Adjusting the Aspect Ratio of an Embedded YouTube Video

<!DOCTYPE HTML> <head> <style> body { overflow: hidden; margin:0; } </style> </head> <body> <iframe id="video" src="https://www.youtube.com/embed/U4c9bBeUe4M?modestbranding=1&sh ...

Speedy Guide to Referencing Variables in JavaScript

I'm hoping for some clarification on this topic. Let's imagine I have 2 global variables: var myarray=[1,3,5,7,9],hold; and then I execute the following code: function setup() { alert (myarray[0]);//displays 1 hold=myarray; alert (hold);//seem ...

Resulting JSON output retrieved from the database

Greetings! I have retrieved the JSON data below from my database: [{ "0": "1", "id": "1", "1": "Hakob", "name": "Hakob", "2": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee8f8c8dae8b838f8782c08d8183"> ...

Hiding a Component: Achieving Smooth Behavior with Timer and onPress

My goal is to create a user interface where tapping the screen displays a <TouchableWithoutFeedback> component, which should automatically disappear after 4 seconds. Additionally, I want the user to be able to tap on the displayed component to hide ...

Coordinated Universal Time on the Website

I am currently developing a website that will be exclusively accessible through the intranet, but it targets users across Australia. Recently, I have been instructed to explore the idea of incorporating UTC time on the site. I am contemplating how I can i ...