Baner
Baner

Reputation: 51

Getting rid of undefined in select options

I have code which reads an uploaded text file and sorts it as options for different <select>. Since i am using for loop and setting it less than file.length. All the options from text file are read correctly but once the text is done, the rest of the options show up as undefined. I wanted to know how to get rid of these undefined? If confusing, please comment below for further explanation.

Upvotes: 0

Views: 69

Answers (2)

Arif
Arif

Reputation: 1643

I've updated your code. Check this Fiddle. It Worked for me for .txt file with content Arif, John, Sonya, SuperGirl, The Flash, Batman, Suparman

i added if statement to for loop, and combined your 3 loops into one

for (var i = 0; i < results.length; i=i+3) {
      $('#name').append('<option val="1">' + results[i] + '</option>');
      $('#name2').append('<option val="1">' + results[i] + '</option>');
      if(typeof results[i+1] !== 'undefined') {
         $('#address').append('<option val="1">' + results[i+1] + '</option>');
         $('#address2').append('<option val="1">' + results[i+1] + '</option>');
      }
      if(typeof results[i+2] !== 'undefined') {
         $('#size').append('<option val="1">' + results[i+2] + '</option>');
         $('#size2').append('<option val="1">' + results[i+2] + '</option>');
      }
    }

Upvotes: 1

daymosik
daymosik

Reputation: 140

You should do

for (var i = 0; i < results.length; i=i+3) {

or you should get value from file

$('#name').append('<option value="1">' + file[i] + '</option>');

Upvotes: 0

Related Questions