-1

This is my first question for JavaScript as I want to read data from "1.dat" file into respective text-fields / boxes.

The is structure of "1.dat" file

    3  
    "Caroline Martin","2007 E.L Road","Los Angeles CA 87457",43  
    "Brian Green", "210 AB Street","New York NY 10002",52  
    "Amy Baker","3213 Canta Mount", "Miami FL 33133",61  

3-marker has no of records of 3 individuals: Name, Address1, Address2, Age.

So, how the structure should be coded in JavaScript to read and display the respective data in respective text boxes of HTML.

    <input id="txtName" type='text'/>
    <input id="txtAdd1" type='text'/>
    <input id="txtAdd2" type='text'/>
    <input id="txtAge" type='text'/>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
NimishK
  • 21
  • 1
  • 5

3 Answers3

2

You can`t just open local files automatically (without user interaction) due to security restrictions! you will get "Cross origin requests are only supported for protocol schemes: http, data, ..."

We have to place an input file on the page and do stuff when user select a file.

Edit: code updated to show file data, record by record with Prev/Next buttons

Edit 2: Update to skip empty/incorrect rows:

<!DOCTYPE html>
<html>
<head>
  <title>File read test</title>

</head>

<body>

<p><input type='file' accept='*.dat' onchange='openFile(event)'></p>

<input type='button' id="btnPrev" value="Prev <" onclick="goRecord(-1)" />

<input type='text' id="txtName" />
<input type='text' id="txtAdd1" />
<input type='text' id="txtAdd2" />
<input type='text' id="txtAge" />

<input type='button' id="btnNext" value="> Next" onclick="goRecord(+1)" />


<script type="text/javascript">
  var data = [], cur;
  var inputs = ["txtName", "txtAdd1", "txtAdd2", "txtAge"]; //id of inputs

  function openFile(event) {

    var input = event.target;

    var reader = new FileReader();

    reader.onload = function () {
      var text = reader.result;
      //if (text!=null && text.length>0)
      var lines = text.split(/\r?\n/g); //split by newline chars to get all lines as array
      var k = -1;
      for (var i = 1; i < lines.length; i++) { //skip first line as it is Nlines
        var r = lines[i].replace(/"/g, "").split(","); //remove quotation marks and split to cols
        if (r.length == inputs.length) { //this row has correct number of columns (4)
          k++;
          data[k] = [];
          for (var j = 0; j < r.length; j++) {
            data[k][j] = r[j];
          }
        }
      }
      cur = 0; dispRecord(cur); //go to first record
    };

    reader.readAsText(input.files[0]);
  }

  function dispRecord(r) {
    var n = data[r].length;
    for (var j = 0; j < n; j++) {
      document.getElementById(inputs[j]).value = data[r][j];
    }
  }

  function goRecord(step) {
    var k = cur + step;
    if (k < 0) k = 0; else if (k >= data.length) k = data.length - 1;
    cur = k;
    dispRecord(cur);
  }

</script>

</body>
</html>
S.Serpooshan
  • 7,608
  • 4
  • 33
  • 61
  • @S. Serp Very well presented and explained. At present Got It. Actually wanted to have only four text fields i.e Name, Add1, Add2 and Age. with Next and Previous buttons wanted to see the Record Set – NimishK Jan 22 '17 at 11:16
  • you are wellcome! if its ok, please choose it as accepted answer to vote up coders (click on tick mark at left side of answer) ;D – S.Serpooshan Jan 22 '17 at 11:21
  • any other way to achieve what i wanted. I am totally new to this. – NimishK Jan 22 '17 at 15:05
  • code updated to show file data as record by record using Prev/Next buttons. please check it now – S.Serpooshan Jan 23 '17 at 05:31
  • @S. Serp Vow This is what i wanted. Probably at the last record of 1st id txtName when pressed Next it goes blank but other three text Ids remain intact. FYI – NimishK Jan 23 '17 at 10:55
  • maybe you have a blank line at last row of file, i'll update the code to skip such empty row – S.Serpooshan Jan 23 '17 at 11:01
  • please check updated answer, edited to skip empty/incorrect rows – S.Serpooshan Jan 23 '17 at 11:16
0

I build an example, how to read and parse data from dat file, and assigning it into text fields:

1.dat file structure

3  
"Caroline Martin","2007 E.L Road","Los Angeles CA 87457",43  
"Brian Green", "210 AB Street","New York NY 10002",52  
"Amy Baker","3213 Canta Mount", "Miami FL 33133",61

HTML

<form>
<input id="txtName1" type='text'/>
<input id="txtAdd11" type='text'/>
<input id="txtAdd21" type='text'/>
<input id="txtAge1" type='text'/>

<input id="txtName2" type='text'/>
<input id="txtAdd12" type='text'/>
<input id="txtAdd22" type='text'/>
<input id="txtAge2" type='text'/>

<input id="txtName3" type='text'/>
<input id="txtAdd13" type='text'/>
<input id="txtAdd23" type='text'/>
<input id="txtAge3" type='text'/>
</form>

Javascript

var client = new XMLHttpRequest();
client.open('GET', '1.dat');
client.onload = (function(){

var txt = client.responseText;

var arr = [];
var lines = txt.split('\n');

for(j=1; j < lines.length; j++)
{
  lines[j] = lines[j].replace(/["]/g,'');
  arr[j] = lines[j].split(",");
  document.getElementById('txtName'+j).value = arr[j][0];
  document.getElementById('txtAdd1'+j).value = arr[j][1];
  document.getElementById('txtAdd2'+j).value = arr[j][2];
  document.getElementById('txtAge'+j).value = arr[j][3];
}

})
client.send(null);

Whole code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Template</title>


  </head>
  <body>

<form>
<input id="txtName1" type='text'/>
<input id="txtAdd11" type='text'/>
<input id="txtAdd21" type='text'/>
<input id="txtAge1" type='text'/>

<input id="txtName2" type='text'/>
<input id="txtAdd12" type='text'/>
<input id="txtAdd22" type='text'/>
<input id="txtAge2" type='text'/>

<input id="txtName3" type='text'/>
<input id="txtAdd13" type='text'/>
<input id="txtAdd23" type='text'/>
<input id="txtAge3" type='text'/>
</form>
<SCRIPT TYPE="text/javascript">


var client = new XMLHttpRequest();
client.open('GET', '1.dat');
client.onload = (function(){

var txt = client.responseText;

var arr = [];
var lines = txt.split('\n');

for(j=1; j < lines.length; j++)
{
  lines[j] = lines[j].replace(/"/g,'');
  console.log(lines);
  arr[j] = lines[j].split(",");
  document.getElementById('txtName'+j).value = arr[j][0];
  document.getElementById('txtAdd1'+j).value = arr[j][1];
  document.getElementById('txtAdd2'+j).value = arr[j][2];
  document.getElementById('txtAge'+j).value = arr[j][3];
}

})
client.send(null);




</SCRIPT>


  </body>
</html>
L. Vadim
  • 539
  • 3
  • 12
  • @L Vadim with your HTML and Js file nothing working out – NimishK Jan 22 '17 at 10:07
  • where you 1.dat located? – L. Vadim Jan 22 '17 at 10:13
  • it is located in "C:\Test-Trial1\1.Dat". Still nothing works. My i know why so many text fields are generated – NimishK Jan 22 '17 at 10:31
  • you have to put your 1.dat to root of your domain. i generated group of fields for each record. – L. Vadim Jan 22 '17 at 10:35
  • at present just want to see the records from "C:\Test-Trial1\1.Dat". Will it be possible to see without var client = new XMLHttpRequest(); client.open('GET', '1.dat'); client.onload = (function(){ Have also not reached to Domain and server level FYI – NimishK Jan 22 '17 at 10:44
  • you can't test the code without dev environment or production. put the code on domain and you will see the power of it – L. Vadim Jan 22 '17 at 11:57
0

I tried below in achieving what i want to achieve but failed

<!DOCTYPE html>
<html>
<head>
 <title>File read test</title>
</head>
<body>

<script type="text/javascript">
 var cur = 3;
 var openFile = function (event) {
 var input = event.target;

 var reader = new FileReader();
 reader.onload = function () {
 var text = reader.result;
 var lines = text.split(/\r?\n/g);
 var n = parseInt(lines[0], 10); //10 is radix
 var s = "", i = 0;
 for (var c = 0; c < n; c++) {
  var row = lines[++i].replace(/"/g, "").split(","); //remove quotation marks and split to cols
 for (var t = 0; t < 4; t++) {
   s += "<input type='text' id='txtName' value=\"" +  row[t].replace(/^\s+|\s+$/g, "") + "\" /> \r\n";
  }
  s += "<br/>";
}
//if (text!=null && text.length>0)
document.getElementById('myConainer').innerHTML = s;
};
reader.readAsText(input.files[0]);
};

function dispValue() {   
   document.getElementById('txtName').value = Names[i];   
   document.getElementById('txtAdd1').value = Add1[i];   
   document.getElementById('txtAdd2').value = Add2[i];   
   document.getElementById('txtAge').value = Age[i]; 
 }
function cmdNext() {    
if(i<cur-1) {      
   i = i + 1;      
  dispValue();    
 }
 }

function cmdPrevious() {   
 if(i>0) {      
  i = i - 1; 
 dispValue(); 
} 
}      

</script>
<input type='file' accept='*.dat' onchange='openFile(event)'> <br/>
<div id="myConainer">
</div>
</body>
</html>

What exactly needs to be done ? because when Presseing next command should display another record and pressing previous button should show previous record ie why only four text boxes to read all 3 records repectively. so basically Each Name Add1 Add2 and Age to read in respective 4 textboxes from 1.dat file

NimishK
  • 21
  • 1
  • 5