Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

White spaces getting removed on generating csv files from HTML dropdown list

I want to get a csv file downloaded with the white spaces preserved in between the words.

HTML

<select id="ddl">
   <option value="1">One apple</option>
   <option value="2">Two Oranges</option>
   <option value="3">Three Grapes</option>
</select>

JAVASCRIPT

var ddlArray= new Array();
var ddl = document.getElementById('ddl');

for (i = 0; i < ddl.options.length; i++) {
  ddlArray[i] = ddl .options[i].text;
}

var csvRows = [];
for (i = 0; i < ddlArray.length; i++) {
   csvRows.push(ddlArray[i]+",");
}
var csvString = csvRows.join("%0A");


var a = document.createElement('a');

a.href = 'data:attachment/csv,' + csvString;
a.target = '_blank';
a.download = 'sampleDownload.csv';

document.body.appendChild(a);
a.click();

When I am executing the above code, a sampleDownload.csv is getting downloaded, but the option values are getting trimmed so that all the white spaces are lost. Example "OneApple" instead of "One Apple". Will it be possible to preserve the white spaces in the csv file?

If I execute an alert the value do contain the white space.

Please help.

The snippet can also be found in JSFiddle: Click here: http://jsfiddle.net/p25x8gfw/8/

This will download a samleDownload.csv on your machine. Works in Chrome and Firefox.

like image 505
Gourab Chakraborty Avatar asked Feb 10 '23 19:02

Gourab Chakraborty


1 Answers

Try This...

var ddlArray= new Array();
var ddl = document.getElementById('ddl');
for (i = 0; i < ddl.options.length; i++) {
   ddlArray[i] = ddl .options[i].text.replace(' ', '%20');
}

var csvRows = [];
for (i = 0; i < ddlArray.length; i++) {
    csvRows.push(ddlArray[i].replace(' ', '%20')+",");}


    var csvString = csvRows.join("%0A");


var a = document.createElement('a');

a.href = 'data:attachment/csv,' + csvString;
a.target = '_blank';
a.download = 'sampleDownload.csv';

document.body.appendChild(a);
a.click();

Here csv file consider %20 is whitespace

like image 169
MaThar Beevi Avatar answered Feb 12 '23 08:02

MaThar Beevi