3

I need to load the text file data into a javascript array and define a dynamic form using html.

I tried below code for extracting data from text file and to store in a javascript array and it works as long as it is in .js file

var fs = require('fs');
var textByLine = fs.readFileSync('123.txt').toString().split("\n");
console.log(textByLine);

but when I embed it inside my html file this doesn't work.

below is my html code. for now I am just forming an array with months but i need to replace it with array taken from the text file.

<html>
<head>
<title></title>
<META NAME="DESCRIPTION" CONTENT="">
<META NAME="KEYWORDS" CONTENT="">


<script language="javascript">
var dt=new Date();
var dt_month=dt.getMonth() +1;
//alert(dt_month);
function addOption(selectbox,text,value )
{
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

function addOption_list(){
var month = new Array("January","February","March","April","May","June","July","August",
"September","October","November","December");
for (var i=0; i < month.length;++i){
addOption(document.drop_list.Month_list, month[i], month[i]);
document.drop_list.Month_list.options[i].selected=true;
}
}
</script>
</head>

<body onLoad="addOption_list()";>
You can see the view-> Source of this page. 
<br><br>
<FORM name="drop_list" action="yourpage.php" method="POST" >

<SELECT  NAME="Month_list">
<Option value="" >Month list</option>
</SELECT>
</form>


</body>
</html>

I gave the 3 line code which is working independently as a .js file inside addOption_list function in above code and it doesn't work. Appreciate help on this.

Thanks in advance

Kishan
  • 197
  • 1
  • 1
  • 6

1 Answers1

1

The FileSytem (fs) module is for NodeJS applications so needs to be in .js file. If you want to load the file into your html you can use Ajax instead. This may work:

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this.responseText);
    }
  };
  xhttp.open("GET", "123.txt", true);
  xhttp.send();
}

function myFunction(data) {
  var textByLine = data.split("\n");
  console.log(textByLine);
}

loadDoc();

</script>
David
  • 84
  • 3
  • Thanks David for the code. I added above function in my script and tried to push elements of textByLine to my default array. it's not happening. I am not getting any error but it's not taking elements dynamically into the drop down from that array. how can we debug this kind of code ? Appreciate your time and effort thanks a bunch – Kishan Apr 18 '19 at 08:06
  • Follow this: https://stackoverflow.com/questions/9895082/javascript-populate-drop-down-list-with-array – David Apr 18 '19 at 19:55