Stelios Voskos
Stelios Voskos

Reputation: 17

Array into datalist

Well, I was here again 2 days ago for the same issue, but it seems that it's still not working. So the task is to pass an array that it's fields are CSV data. I got an advice to to it like this:

<datalist id="stelios">

</datalist>
<script type="text/javascript" src="jquery.js"></script>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object`

// Loop through the FileList
        for (var i in files) {

            var reader = new FileReader();

            $('#stelios').append('<option value=' + files[i] + '>');
        }
    }

document.getElementById('stelios').addEventListener('change', handleFileSelect, false);
</script>

It seems that I don't get the data yet though. Any ides?

Upvotes: 0

Views: 738

Answers (1)

Sumurai8
Sumurai8

Reputation: 20737

You are using for( var i in files ). This will loop through all values in files, as well as anything that has been added to the Object prototype. (This is bad) You'll need to filter the output of this.

The next line contains var reader = new FileReader();. There doesn't seem to be any reference to this in your for loop, so delete it.

The next line is $('#stelios').append('<option value=' + files[i] + '>');. It creates a certain 'option' element and appends this to an element with an id of stelios. This seems to be correct. However, the value of this option element is set to files[i] without quotes... Which will most likely result into a mess. You need to change it to:

for( var i in files ) {
  if( files.hasOwnProperty( i )) {
    //Removed unneeded FileReader
    $('#stelios').append('<option value="' + files[i] + '">');
  }
}

I am assuming that you checked that files contains the data you expect it to contain. I have honestly no clue what you are trying to achieve with the onchange handler.

Upvotes: 1

Related Questions