Search code examples
javascriptjqueryhtmldropdown

Export html table with dropdown lists to a CSV file using jquery/javascript


As written in the title , I have HTML table that has few columns where the user has to select values from dropdown lists. What I want to do is to be able to export this table to a CSV file . I found online a jquery plugin but I have a problem with the dropdown lists. It gives back all of the option for each row instead the ones that are selected. I tried fixing this but I failed.

The JQuery plugin and and example table are in the jsfiddle:

https://jsfiddle.net/bLa8pn74/

I tried to insert this:

if($(this).find('select').each(function(){
                    line.push(_quote_text($(this).find("option:selected").text()));
                }));

But it only printed the head row. I now it should be simple change but I just can't figure it out .

EDIT: I would like that my solution is without creating new table.

EDIT 2: I tried this code also :

if($(this).find('select')){
    line.push(_quote_text($(this).find('option:selected').text()));
            }
    line.push(_quote_text(_trim_text($(this).text())));

And it gives me the selected option but also afterwards all dropdown options, and extra "","", where it finds an empty cell.

And If I add "else" before the second "line.push" then it returns only the selected values and everything else is empty.


Solution

  • I found what was missing. I just needed the ".length" in my if condition.

    if($(this).find('select').length){
              line.push(_quote_text($(this).find('option:selected').text()));
     }else{
           line.push(_quote_text(_trim_text($(this).text())));
           }