The function created from the JavaScript code is malfunctioning

I stumbled upon this JavaScript code online:

var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");

link.click();

After running it, the file my_data.csv is generated and downloaded automatically. Now, I want to modify it so that when a user clicks a button, the code executes. I attempted to convert it into a function called Testing() and updated my link as follows:

<a href="#" onClick="javascript:Testing()">Test</a>

However, placing the code inside a function seems to break it. What am I doing incorrectly?

The console error message states 'Testing is not defined.'

For reference, here's a jsfiddle: http://jsfiddle.net/F6CWF/

Answer №1

You might want to consider implementing a solution similar to the following:

Here's an example of how you can set it up:

<button id='download-btn'>Download CSV</button>

In your JavaScript file, you can add the following function:

document.querySelector( '#download-btn' ).addEventListener( 'click', function () {
    var encodedUri = encodeURI( csvContent );
    var link = document.createElement( 'a' );
    link.setAttribute( 'href', encodedUri );
    link.setAttribute( 'download', 'my_data.csv' );
    link.click();
});

If you need further assistance, feel free to share a fiddle with us.

Answer №2

When faced with that problem, there are multiple solutions available:

Solution 1

var link = document.createElement("a");
link.href = "javascript:Testing()";

Solution 2

var link = document.createElement("a");
link.onclick = Testing;

If the examples above do not work, consider using the inline variants:

Inline Solution 1

var link = document.createElement("a");
link.href = "javascript: here goes the function's body";

Inline Solution 2

var link = document.createElement("a");
link.onclick = function() {
  // here goes the function's body
};

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

Setting up Material UI Icons in your React js project

I've been having trouble installing the Material UI Icons package with these commands: npm install @material-ui/icons npm install @material-ui/icons --force npm i @mui/icons-material @mui/material Error messages keep popping up and I can't see ...

As I iterated over the Vehicles API data, I encountered an issue while trying to access specific Vehicle information. I received an error message stating "Cannot read property 'id' of undefined

Exploring the realms of Angular, with some experience in older versions, I find myself faced with a challenge involving two APIs - "/vehicles" and "/vehicle/{id}". The process involves fetching data from "/vehicles", iterating through it to match IDs, the ...

What is the correct procedure for utilizing variables in the parseJson function when working with string objects?

While working with the parseJson function, I have encountered a challenge where I need to incorporate a variable within three objects. Is there a way to merge a variable with the value of one object? Alternatively, can I utilize a third object to store t ...

Convert a JSON array with a single element into a valid JavaScript object

Within my programming scripts, I frequently utilize PHP arrays with numeric keys. However, these keys are not necessarily sequential from 0 to n; they can be randomly chosen. Specifically, I am working on a script that organizes scheduled events at specifi ...

Is it possible to utilize $regex alongside $all in mongoDB?

In my current project, I am facing a challenge where I need to handle an array of strings received from the frontend. Each document in my mongoDB database also has its own array of keywords. The tricky part is that the strings sent from the frontend migh ...

HTML form submission with a grid of multiple choice options

I have created my own multiple choice grid: <div style="overflow-x:auto;"> <table class="w-100"> <tr> <td class="border"></td> <td class="border">Yes</td> <td class="border">No</ ...

Deactivating checkboxes once the maximum selection has been made through jquery

I need assistance with my jQuery code that is supposed to disable checkboxes in a multidimensional array after reaching the maximum number of selections. However, I am having trouble identifying the issue within the code. Any guidance would be greatly ap ...

Using a jquery function within a Laravel view

I am trying to retrieve a selected item from a dropdown menu using jQuery and then redirect it to a controller function. This function will return some data to be displayed based on the selected item. I could really use some assistance with this. Here is m ...

Issue: Unable to locate the module 'babel-code-frame' in VUEJS (ESLINT)

Here are the current versions: -npm: 6.14.4 -node: v10.19.0 -eslint: v5.0.1 -linux: ubuntu 20.04 This is my script: vue create vue1 cd vue1 npm run serve This is my package.json: { "name": "vue1", "version": "0. ...

Navigate a first person simulation using three.js and control your movements with the keyboard arrow

To access my reference material, please go to http://jsfiddle.net/fYtwf/ Overview I am working on a basic 3D simulation using three.js where the camera is surrounded by cubes in three dimensions. These cubes serve as a visual guide to where the camera is ...

JavaScript encountering a NaN value

I'm encountering an issue where I am receiving a NaN when attempting to summarize columns of a report. Additionally, my query is only retrieving 1 row of data, but the grid is displaying 2 rows. Does anyone have any suggestions on how to resolve this ...

What is the best way to manage data that arrives late from a service?

Within my Angular application, I have a requirement to store data in an array that is initially empty. For example: someFunction() { let array = []; console.log("step 1"); this.service.getRest(url).subscribe(result => { result.data.forEach( ...

The updateItem function in the JSGrid controller was not called

Currently, I am working on a project involving js-grid. However, I have encountered an issue where the updateitem function of the controller is not being invoked when attempting to update a column field. Additionally, the field resets to its old value wi ...

Is it possible to continuously generate webpages using AJAX?

Is there a way to achieve an infinite scrolling effect in all directions using ajax requests without the need for flash or silverlight? If anyone has an example of this, I would love to see it! Thank you for your time. ...

Can the Automator tool capture a specific section of a website in a screenshot?

Is it possible to use automator to navigate through a store's website category and open each product in a new tab? Alternatively, is there a software that can extract all the product URLs from a specific website? For example, this website has 14 prod ...

numerous ajax requests and array variables

I find myself in an interesting situation with my application, where I need to handle a couple of scenarios. Firstly, I have to fetch data from two different sources using AJAX calls. Secondly, I need to compare and manipulate this data. If the values matc ...

Angular: Where does the problem lie - with the application or the deployment?

Currently, I am in the process of creating my own personal website using Angular(v4+). I understand that Angular may seem like a complex framework for a simple website, but I am using it because I am eager to improve my skills with it. During development, ...

Determining Equality in JavaScript: Comparing 2 Objects

I'm currently working with 2 objects that will always have the same amount of properties, but their values may vary. In my attempt to check if the two objects hold the same values, I decided to use the .every method. However, all results are returnin ...

Ways to retrieve information from a URL using the .get() method in a secure HTTPS connection

As I work on handling user input from a form using node.js, express, and bodyParser, I encounter an issue. Even after using console.log(req.body), the output is {}. This is puzzling as there is data in the URL when the form is submitted successfully at htt ...

Can you share tips for passing a variable from a post request to a function that accepts parameters as a string or an array of strings in Node.js?

I am struggling to insert the variable named query into the end of the prompt. I attempted to use template literals but it was unsuccessful. (async () => { const gbtResponse = await openai.createCompletion({ model: "text-davinci-002", prompt ...