简体   繁体   中英

Create and populate select element from csv file using javascript

Having a bit of a problem looping through the csv file. I am also not sure if there isn't a simpler way of loading the text file. I know a for each loop makes sense but I am not sure about the individual item in a csv file. I want the whole line of text and I assign the two piece of text to the value and choice parts of the option. Any advice to clean this up?

*UPDATE incorporating the suggestions below. Error free but the created element is not being captured by my CSS file so the formatting is off and the select box only shows blanks.

<script>
             function processCSV(file,parentNode)
             {
                var frag = document.createDocumentFragment()
                , lines = file.split('\n'), option;                 

                for (var i = 0, len = lines.length; i < len; i++){
                    option = document.createElement("option");
                    option.setAttribute("value", lines[i]);
                    option.innerHTML = lines[i];                        
                    frag.appendChild(option);
                    }
                plant_select.appendChild(frag);
             }

             var plant_select = document.createElement("select");  
             var intial_option = document.createElement("option");
             var datafile = '';
             var xmlhttp = new XMLHttpRequest();

             plant_select.setAttribute("class", "selectbox");   
             plant_select.setAttribute("id", "plant_select");
             intial_option.setAttribute("value","")
             intial_option.setAttribute("disabled","disabled")
             intial_option.setAttribute("selected","selected")
             intial_option.innerHTML = "Please select a Plant";
             plant_select.appendChild(intial_option)

             xmlhttp.open("GET","http://localhost:8080/res/plants.csv",true);
             xmlhttp.send();


             xmlhttp.onreadystatechange = function()
             {
                if(xmlhttp.status==200 && xmlhttp.readyState==4)
                {
                    processCSV(xmlhttp.responseText, plant_select);
                }
             }
        </script>

Supposing the display text is the first element, value as second in the CSV, and that you know your CSV is properly formatted.

var dflines = datafile.split("\n");
for (var i=0; i<dflines.length; i++) {
    dflines[i] = dflines[i].split(",");
    plant_select.options[plant_select.options.length+1] = new Option(dflines[i][0],dflines[i][1],false,false);
}

Will add new select options to your current select.

There are a number of things you need to do here:

  • You need to process your text correctly. Don't use for...in on strings or arrays. It isn't doing what you want it to do. Instead split the file into an array of lines and process these lines.
  • In your processing loop, you are modifying the DOM on every single run. This causes reflows and repaints unnecessarily. Instead, use a document fragment .
  • You need your processing code in your callback, or preferably in a function called in your callback.

So your processing function:

    function processCSV(file,parentNode){
      var frag = document.createDocumentFragment()
        , lines = file.split('\n')
        , option
        ;
      for (var i = 0, len = lines.length; i < len; i++){
        option = document.createElement("option");
        option.setAttribute("value", "Choice"); 
        frag.appendChild(option);
      }
      parentNode.appendChild(frag);
    }

Then your XHR callback:

xmlhttp.onreadystatechange = function(){
  if(xmlhttp.status==200 && xmlhttp.readyState==4){
    processCSV(xmlhttp.responseText, plant_select);
  }
}

This doesn't do any per-line processing, but I'd need more information from you to be of any help there. You likely want to split by comma and look at individual data items, which you could do with a nested loop in the processCSV function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM