0

I have a department.txt file that contains departments:

Chemistry
Physics
Mathematics
Other

and i want to create a drop down list <select> by importing this file in my HTML. How can i do it using Javascript? There are 50+ departments in file , so creating <option> for every department will not be a good idea.

4
  • have you try something ? Commented Nov 6, 2015 at 5:15
  • As far as I know javascript will not let you access the file system, so you will not be able to open department.txt with JS. Commented Nov 6, 2015 at 5:18
  • @ShailendraSharma yes. I have tried using php to import the file and create list inside javascript. That doesn't work. Commented Nov 6, 2015 at 5:20
  • @angelcool.net Alright. is there anyother way to populate the list? like using AJAX or any other mehtod? Commented Nov 6, 2015 at 5:22

1 Answer 1

1

To read txt file, you need to make an ajax call to department.txt and iterate departments like this:

function readFile() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      var res = xhttp.responseText;
      res = res.split('\n');
      var html = '<select name="department">';
      res.forEach(function(item) {
        html += '<option value="' + item + '">' + item + '</option>';
      });
      html += '</select>';
      document.body.innerHTML = html;
    }
  };
  xhttp.open("GET", "department.txt", true);
  xhttp.send();
}
readFile();
Sign up to request clarification or add additional context in comments.

Comments

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.