0

I have two buttons ... when clicked they display some text in a input field. I use some simple javascript to select which text to display, the one defined under the button with id="blabla1" or the one under the button with id="blabla2". Is it possible to display the text defined in an external .txt file?

It is working fine with the text defined as value under the input button:

<input type="hidden" id="SupSite1Title" value="Subsite1 Title!"><br>

but i want text from a txt file instead.

<body>  

<div id="leftnav">
<ul>
<li><input type="text" id="TextField1"><br><br></li>
</ul>   
</div>

<div id="rightnav">
<ul>
<li><button id="blabla1" onclick="myFunction1()">Side1</button></li>
<li><button id="blabla2" onclick="myFunction2()">Side2</button></li>
</ul>   
</div>


<input type="hidden" id="SupSite1Title" value="Subsite1 Title!"><br>
<input type="hidden" id="SupSite2Title" value="Subsite2 Title!"><br>


<script>
function myFunction1() {document.getElementById("TextField1").value =document.getElementById("SupSite1Title").value;
}
</script>
<script>
function myFunction2() {document.getElementById("TextField1").value =document.getElementById("SupSite2Title").value;
}
</script>

3 Answers 3

1

If you want to display the text content of the .txt file ... you can use an API called FileReader API (you need to check if your browser supports that)

here is how you can do it :

UPDATED :

var file1 = document.getElementById('file1');
var file2 = document.getElementById('file2');

document.getElementById('bOne').addEventListener("click", function(){getFile(file1)})
document.getElementById('bTwo').addEventListener("click", function(){getFile(file2)})


function getFile(target) {
	const input = target;
  if ('files' in input && input.files.length > 0) {
	  placeFileContent(
      document.getElementById('display'),
      input.files[0])
  }
}

function placeFileContent(target, file) {
	readFileContent(file).then(content => {
  	target.value = content
  }).catch(error => console.log(error))
}

function readFileContent(file) {
	const reader = new FileReader()
  return new Promise((resolve, reject) => {
    reader.onload = event => resolve(event.target.result)
    reader.onerror = error => reject(error)
    reader.readAsText(file)
  })
}
label {
display : block;
margin-top : 40px;
margin-bottom : 20px;
}
<label for="file1">Upload file 1 : </label>
<input type="file" accept=".txt" id="file1"  name="file1">

<label for="file2">Upload file 2 : </label>
<input type="file" accept=".txt" id="file2"  name="file2">


<button id="bOne">Display file1</button>
<button id="bTwo">Display file2</button>

<label for="file2">Selected file :  </label>
<input type="text" id="display" for="display">

METHOD N°2 (data fetching from a server) :

function fetchData(buttonNumber) {
  var btn1 = document.getElementById('b1')
  var btn2 = document.getElementById('b2')
  var display = document.getElementById('display')
  //fetching data
  if (buttonNumber == 1) {
    //replace 'file1.txt' with your file URL
    fetch('file1.txt').then(x => {
      x.text().then(function(text) {
        display.value = text
      });
    })
  } else {
    //replace 'file2.txt' with your file URL
    fetch('file2.txt').then(x => {
       x.text().then(function(text) {
        display.value = text
      });
    })
  }
}
#b1,
#b2 {
  display: block;
  margin: 40px;
}
<button id="b1" onclick="fetchData(1)">Get file 1 and show it</button>
<button id="b2" onclick="fetchData(2)">Get file 2 and show it</button>

<label for="file2">Selected file :  </label>
<input type="text" id="display" for="display">

Sign up to request clarification or add additional context in comments.

16 Comments

Hi Dadboz, thanks a lot for your response. My overall goal is to have one textfield and three buttons. If the user pres button1 then the content of "textfile1.txt" soud be shown in in the textfield. If the user pres button2 then the text content of "textfile2.txt" should be displayed in the text field. I am completely new i html/java. Is my solution a good one or would you go for something else?
@Birch78 it's unclear what you are asking .... please do update your Question explaining the expected results and more details on what are you trying to do ... you need to upload .txt files first then it's up to you wherever you want to show them
sorry for not being very clear. I want to have one text field on my html site. Then I have two *.txt files (file1.txt and file2.txt). Then I want to have two buttons on my html site and if the user select button1 then the content of file1.txt should appear in the text field. If the user then click button 2 the content of file2.txt should appear in the text filed. Only one button should be selected at the time and therefore only one *.txt content visible in the text field at the time. I hope this is more clear
@Birch78 Thanks for clearing out ... so now you need TWO inputs (with type="file" ) to upload the two .txt files right ? and another input (with type="text") to display the text of the selected file .txt ( so in total you need 3 inputs ) ... and also we need 2 buttons to select which file we want to display (file1.txt or file2.txt) right? if yes ....then i will update my answer with the previous changes
@Birch78 i updated the answer you can run it now again
|
0

If you want to read the contents of a text file you cannot load it from local file system. You should put it on server and load it from there.

Comments

0

Give the input field the attributes type="file" and accept=".txt", and that should work

<input type="file" accept=".txt" />

And you can read this .txt file using node.js(Also you can read it with vanilla js), But i prefer node.js like this

const fs = require('fs');
const fileData = fs.readFileSync('fileName.txt', 'utf-8');
console.log(fileData) // Whatever inside .txt file

Update according to comment:

Suppose in your project folder, you have one index.html file and one index.js file. Create two .txt file named as file1.txt and file2.txt And write something on those file. NOTE: For simplicity i am writing solution using jQuery.

index.html

<body>
    <p id="text-field"></p>
    <button id="btn1">Button 1</button>
    <button id="btn2">Button 2</button>
</body>

index.js

const fs = require('fs');
let fileData = '';

$('#btn1').click(()=> {
    fileData = fs.readFileSync('file1.txt', 'utf-8');
    $('#text-field').append(fileData);
});

$('#btn2').click(()=> {
    fileData = fs.readFileSync('file2.txt', 'utf-8');
    $('#text-field').append(fileData);
});

That's it. According to button click text will be append into p element.

You can handle two button click with one function also, like this

$('button').click(event => {
    event.stopImmediatePropagation();
    event.stopPropagation();

    if($(event.target).attr('id') === 'btn1') {
        fileData = fs.readFileSync('file1.txt', 'utf-8');
        $('#text-field').append(fileData);
    }else if($(event.target).attr('id') === 'btn2') {
        fileData = fs.readFileSync('file2.txt', 'utf-8');
        $('#text-field').append(fileData);
    }
});

5 Comments

Hi Robin, thanks a lot for your response. i hope you are ready for a new question. My overall goal is to have one textfield and three buttons. If the user pres button1 then the content of "textfile1.txt" soud be shown in in the textfield. If the user pres button2 then the text content of "textfile2.txt" should be displayed in the text field. I am completely new i html/java. Is my solution a good one or would you go for something else?
According your comment, you need to define two separate button click event listener - one for button1 and another for button2. And you need push your textfile1.txt and textfile2.txt into database or server. Then you can read it according to button click. Otherwise no need any input field. Just write two .txt file in your project folder and read it according to button click.
I'm sorry for being so st...., but could you show me how this could be implemented in the my code above? I would appreciate it a lot.
@Birch78 see updated answer please. If you find this your expected answer, please mark it as Accept and Upvote :) ---Happy Coding---
I will accept and upvote immediately. Do you have any idea what the problem could be?

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.