JavaScript search in many txt files - javascript

I have a search bar in HTML page and I have many text files and I want to do a search with Javascript to find String in all the text file. I want to know if its possible to do it with Javascript. I can do it search in one text but not many. Here is search script and the HTML.
function readTextFile(file,str)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
if(allText.search(str) != -1){
alert("exist");
alert(location.pathname);
}else{
alert("not exist");
}
}
}
}
rawFile.send(null);
}
<div>
<form name="search" onsubmit="return readTextFile('All-html.txt',this.string.value);">
<input name="string" onchange="n = 0;">
<input type="submit" value="Go">
</form>
</div>
Thanks.

Assuming your function works (readTextFile(file,str)), I would write a new function that iterates over the files list and call readTextFile for each file. Also return true/false if the str was found.
function searchAllfiles(str){
var files = ["file1", "file2", "file3"];
files.forEach(function(filename) {
found = readTextFile(filename, str);
if (found){
alert(str + " was found in " + filename);
}
});
}
Edit:
You can't get the files list from the server using only JS.
1 Option is to keep track on the clients side of the files the user adds dynamically
Second option is to pass the list from the server. Maybe you can maintain the files list inside 1 file and get the paths by reading it or build a service that will return the files list and then call this service with an Ajax call via JS.

Related

How can I display textarea client input on website without changing URL?

I am attempting to implement a feature on my website, where a user can input a comment into a textarea and have it display the comment, below the comment box. For backend I am using bottle. At the moment, bottle is recognizing the input, and when input is submitted, a new url loads displaying only the input of the textarea.
When submitted, I need the textarea input to be displayed below the textarea box, without changing the webpage.
Here is HTML textarea input
<div>
<p>
Add a comment
</p>
<form action="/comment" method="post">
<textarea name="text"></textarea>
<input type="submit" value="Submit">
</form>
</div>
Bottle in main.py
#route('/comment', method = 'POST')
def submit():
com = request.forms.get('text')
print('Printing comment...')
print(com)
return com
index.js, (i'm not sure how to integrate this function)
function loadCom () {
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
console.log(this.response);
document.getElementById("dcom").innerHTML = this.response;
}
};
xhttp2.open("GET", "/comment");
xhttp2.send();
return false
}
Call loadCom() from an event listener.
document.querySelector("form").addEventListener("submit", e => {
e.preventDefault(); // prevent reloading the page
loadCom();
});
loadCom() needs to use the POST method to send the value of the textarea to the controller.
function loadCom () {
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
console.log(this.response);
document.getElementById("dcom").innerHTML = this.response;
}
};
xhttp2.open("POST", "/comment");
xhttp2.send('text=' + encodeURIComponent(document.querySelector('[name="text"]').value);
return false
}

How to not open File upload when parameters are not meet javascript

How to not open the file upload box when input mytextField is null.
<input type="text" id="mytextField">
<input type="file" multiple id="myFileUpload">
<script>
document.getElementById("myFileUpload").addEventListener("click", function () {
var myTextF = document.getElementById("mytextField");
if(myTextF = null || myTextF == ''){
//will not open the file upload
} else {
//let the file upload open
}
});
</script>
You can disable the upload button when textarea is empty and enable it when textarea contains text.
<input type="text" onkeyup="checkField()" id="mytextField">
<input type="file" multiple id="myFileUpload" disabled="disabled">
script:
function checkField(){
var myTextF = document.getElementById("mytextField");
if(myTextF.value.trim() != ""){
document.getElementById("myFileUpload").disabled = false;
}
}
Used the trim() function to prevent empty whitespace texts.
Here you are assigning myTextF to the element, rather than the innerText.
Try with var myTextF = document.getElementById("myTextF").innerText;
If something doesn't work, you could always try to log the output to the console.
In this case, because you are assigning the element, that resolves as TRUE, and it will always try to open the file.
document.getElementById("myFileUpload").addEventListener("click", function () {
var myTextF = document.getElementById("mytextField");
if(myTextF = null || myTextF == ''){
//will not open the file upload
console.log("I should not open file")
} else {
//let the file upload open
console.log("I should open the file")
}
});
" I should open the file"

Accessing value of javascript file input variable

I am trying to get the filepath of the selected file.
Using the debugger, I see that the file has an property called value which is equal to : "C:\fakepath\filename.txt".
However when I try to access file.value, the filepath is equal to null.I am using Java 8, Struts 1.2, Jsps, and Chrome
Javascript:
function validateFile(file)
{
filepath = file.value; /*This is null*/
return true;
}
Html:
<input type="file" id="theFile[0]" onChange="validateFile(this)"/>
Try this:
function validateFile(fileinput) {
var allowed = "pdf,png";
var filepath=fileinput.value;
var ext = filepath.substr(filepath.lastIndexOf('.')+1);
if (filepath = "" || allowed.search(ext) <= -1) {
fileinput.value='';
alert('Invalid file type');
return false;
}
}
<input type="file" id="inputFile" onChange="validateFile(this)"/>
I guess it wasn't too much work after all :)
function validateFile(file)
{
filepath = file.value;
document.getElementById('result').innerText = filepath;
return true;
}
<input type="file" onChange="validateFile(this)"/>
<div id="result">[result will be here]</div>

Combining file size check and file type check - JS validation

So I am trying to validate file uploading before the file itself is uploaded and would like to check for two conditions - whether or not the file is smaller than 5mb and whether or not the file is in an image format.
This is how I am doing it at the moment:
<script>
$(document).ready(function () {
$('input[type=file]').change(function () {
var fileSize = this.files[0].size/1024/1024;
if (fileSize > 5) { alert("Please check the size of your image");
$(this).val('');
}
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(png|jpg|jpeg|gif)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Only image files are supported. Please check the format of your file and try again.');
}
});
});
</script>
It works fine except that if the file is too big and it is removed, the alert for wrong file type fires too because the input has changed.
Is there any better way to get around this? I'd like to check both conditions without the user getting warned about file format if only the image size is wrong. Could I kill the second function if the first one is triggered?
Here is what you can do, create and manage an array of errors, and use it at the end. Click run to see the demo
$(document).ready(function() {
$('input[type=file]').change(function() {
var file = this.files[0],
val = $(this).val().trim().toLowerCase();
if (!file || $(this).val() === "") { return; }
var fileSize = file.size / 1024 / 1024,
regex = new RegExp("(.*?)\.(png|jpg|jpeg|gif)$"),
errors = [];
if (fileSize > 5) {
errors.push("Please check the size of your image");
}
if (!(regex.test(val))) {
errors.push('Only image files are supported. Please check the format of your file and try again.');
}
if (errors.length > 0) {
$(this).val('');
alert(errors.join('\r\n'));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" />

javascript query string

I am learning how to do a query string what html would you use for the following function on the sending and receiving page to see the result of author?
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
I found it at: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
Are they any good query string examples?
I can't quite tell what you are asking but I guess you're looking for a way to test this method and verify its behavior. Here is what I would do, save these contents in an HTML file:
<html>
<body>
<form name="form1">
Key: <input type="text" name="text1" value="author"/>
<input type="button" name="button1" value="Test"/>
</form>
<script>
document.form1.button1.onclick = function() {
alert(getQuerystring(document.form1.text1.value));
}
function getQuerystring(key, default_) {
// your code here...
}
</script>
</body>
</html>
Now you can open your HTML page in a web browser and add a query string like "?author=me&foo=bar". For example, if your file is saved in "C:\tmp\example.html" then your URL should look like this:
file:///c:/tmp/example.html?author=me&foo=bar
The page will show a text field (which says "author" by default) and a button and when you press the button the page will show a popup with the result of running the function with the value you put in the text field. With my example query string, the key "author" should alert "me" and the key "foo" should alert "bar".
http://www.example.com?variable=string&var2=ok&var3=str3
is an example of a query string
<script>
var_this = getQuerystring(var2);
if(var_this == "ok"){
//do this
}else{
// do this
}
</script>
function getQuerystringParameter(name, _default) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return (match && decodeURIComponent(match[1].replace(/\+/g, ' ')) || _default;
}

Categories

Resources