javascript - read file in form with js codeigniter
one text
Solution:
To achieve this you can use split()
to convert the value read from the text file in to an array, with one element per line of text.
Then you can loop through that array and set the values within each textarea
. Try this:
<input type="file" id="id"><br />
<textarea class="result" id="result1" cols="50"></textarea>
<textarea class="result" id="result2" cols="50"></textarea>
<textarea class="result" id="result3" cols="50"></textarea>
<textarea class="result" id="result4" cols="50"></textarea>
let $results = $('.result');
$("#id").on('change', e => {
e.preventDefault();
var reader = new FileReader();
reader.onload = e => {
e.target.result.split(/\r\n/).forEach((text, i) => {
$results.eq(i).val(text);
});
};
reader.readAsText(e.target.files[0]);
});
Note that I applied the same class
attribute to the textarea elements to make the logic much simpler. Generally speaking, incremental id
attributes are an anti-pattern and should be avoided where possible.
Here's a working example in a (as SO snippets are sandboxed and cannot use FileReader
). You'll need to create a text file yourself to see it in action.