I want to create a HTML text field for example I have list of names in txt or csv file I want to call random name from list to that field on button click
Asked
Active
Viewed 1,766 times
1
-
http://stackoverflow.com/questions/13709482/how-to-read-text-file-in-javascript – Zakaria Acharki Dec 20 '15 at 23:53
1 Answers
1
To get HTML from a text file, you could use AJAX
. What you're looking for is probably the xmlHTTPRequest
method. It would look something like this
var xmlHttp = new XMLHttpRequest();
xmlhttp.open("GET","search.txt",true);
xmlhttp.send();
You would then need to parse your file. My source is from this answer here
Javascript Read From Text File
Let's say your html looks like this
<button id="my-button">Generate Random Names</button>
<input type="text" id="my-input" />
The first solution would be to query the button and input elements, and store the result in variables.
var button = document.getElementById("my-button");
var input = document.getElementById("my-input");
Let's say we store our names in a variable like this.
var names = ["Henry", "Joseph", "Mark", "Michael"];
You would then listen for the click
event. And call your function. We can access individual elements in an array by listing the name of an array followed by the index of the element inside braces. We can now set the html of the input element to a random array element.
button.addEventListener("click", function() {
input.value = names[Math.floor(Math.random() * names.length)];
});
Fiddle

Community
- 1
- 1

Richard Hamilton
- 25,478
- 10
- 60
- 87
-
_I have list of names in txt or csv file_, where you get the data from file??!! – Zakaria Acharki Dec 20 '15 at 23:59
-
Dear Sir, I have more than 500+ names . is there any solution to get same data from csv or txt file – Ehsan Qureshi Dec 21 '15 at 00:03
-