1

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>
1
  • you for loops need to be in your callback. oh, and you might want to set a text for the option, else they are all the same and visually blank. new Option("text","value") is handier than createElement for this... Commented Oct 4, 2013 at 18:58

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

wow thank you very much!!! This basically replaces my code. I am going to try and fold this into what I got may have a question or two for follow on.
, lines = file.split('\n'), option ; is giving me a syntax error
@TheCodeNovice Accidental semicolon on the line previous to that one. Removed in edit.
with the setup as it is now. Is there any specific way i need to set up the CSV. The code works but the my text box does not show the choices. its like filled with blanks, the correct amount of blanks but blanks. I do not think its parsing correctly or something
Could you set up a jsfiddle so I can see the code in its current state?
1

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.

2 Comments

ok great this is a lot more compact. Quick follow on is what I am doing now the best way to open a file for this purpose?
I'd probably just have your server-side language encode it into a Javascript variable, as long as the CSV is static. If it's dynamic, encode it into JSON then load it using JQuery. It's really easy to do it that way (PHP - print "var data='".json_encode($array)."';". Running any kind of request on the client side should be avoided if possible (static data or could be included differently), just to avoid coding complexity.

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.