0

i want to download array stored in filtered variable as text file but no file download while running code. If i create an array like this var data = [255,626,626,"xyz"] and use it, i am able to download text file but if i use array named "filtered" in this code, is not downloading as text file.


var x = document.querySelector("#regform > div:nth-child(8) > div > table > thead");
var nodes =x.getElementsByTagName("input");
var text = [];
for ( i = 0; i < nodes.length; i++) {
  var y =nodes[i].getAttribute("name");
  text.push(y);
};
function removeDuplicates(arr) {
  return arr.filter((item,
  index) => arr.indexOf(item) === index);
}
 var filterd = removeDuplicates(text);
var result =  Array.isArray(filterd);
console.log(result);// getting true that means this is array.
var textToBLOB = new Blob([filterd], {type: 'text/plain'});
                 
       var sFileName = 'formData.txt';     // The file to save the data.
       console.log(textToBLOB);

        var newLink = document.createElement("a");
        newLink.download = sFileName;

        if (window.webkitURL != null) {
            newLink = window.webkitURL.createObjectURL(textToBLOB);
        }
        else {
            newLink.href = window.URL.createObjectURL(textToBLOB);
            newLink.style.display = "none";
            document.body.appendChild(newLink);
        }

        newLink.click(); 

3
  • In what case of the if/else does it not get downloaded? Both? Just one? Commented Mar 31, 2023 at 1:57
  • In one case it not get downloaded, when i use variable named "filtered" in this code. Filtered is an array of strings. Commented Mar 31, 2023 at 2:00
  • @rakeshprajapat You have a typo in the first if branch. It should be newLink.href = window.webkitURL.createObjectURL(textToBLOB);, but you assign to newLink itself. After fixing that, your code works. Commented Mar 31, 2023 at 2:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.