Extracting data from text file using javascript - javascript

How can I extract text data from a text file using javascript? I am making an online dictionary. I can code HTML and CSS well but not javascript.
Word Will be entered in first textbox then search button will be clicked and results will be shown in bottom textbox.
The data in text file is like "apple|a juicy fruit"
(without the quotations"
Now I want the text in search field to check up words before "|" sign and if match is found word/words after "|" will be sent to result field.
How can I do this using javascript?
My HTML code for the project is below:
<html>
<head>
<title>Online Dictionary</title>
<style>
.field{
border: 2px solid black;
}
#result_field{
margin-top: 5px;
width: 247px;
height: 100px;
}
</style>
</head>
<body>
<input type="text" placeholder="Enter your word here..." name="search_field" id="search_field" class="field">
<input type="button" value="SEARCH" name="btn" id="btn" class="btn"> <br>
<input type="text" placeholder="Meaning here..." name="result_field" id="result_field" class="field">
</body>
</html>

Try using Ajax.
Ajax is what do a request to a file from a server, so with it you can:
Check velocity of user network;
Get content of file.
See this.
I made few simple functions, you can check them here.
To use one of the functions above you can add lines like these:
$GET('file.txt?c=0',function(result){/* Success function */},function(e){/* Error function */});
$GET('dictionary.txt?anyvalue=0',function(text){alert(text);},function(e){/* Error function */});
/* in ahead of the link you will have to include the ?urlvar=value to the function works, */
/* I still didn't leave the function complete */
Note: case you want to request a file from another server then the file has to allow servers to access it (to allow or not allow you can use PHP or htaccess).
As #Stephan Bijzitter said, you can use PHP (or ASP) - there you can result the right meaning of a word easily.
A example is:
if($_GET['word']=="PC"){echo "Meaning";}
switch($_GET['word']){case "Word":echo "A word?";break;}
/* In PHP, $_GET['word'] returns the value of a parameter in page URL called "word" */

Related

Creating an Equation Solver

I'm honestly just confused on what I should code for this project.
This is for a project I'm working on. Countless attempts I've tried just made me land back to the ground floor.
<!DOCTYPE html>
<html>
<head>
<title>Equation Solver</title>
<style>
/* CSS styles goes here */
form {
margin: auto; /* Centers the Form */
position: center;
text-align: center;
border: 4px solid black;
background:rgb(153, 102, 255);
color: black;
width: 300px;
height: 100%;
padding: 20px 68px;
border-radius: 32px
}
</style>
<script>
//JavaScript code goes here
</script>
</head>
<body>
<h1 align="center"> Solve the Equation </h1>
<form align="center">
<b>Click Me For a Mathematic Equation.</b><br>
<button onclick="ClickMe();">Click Me</button>
</form>
<form align="center">
<b>Submit Your Answer</b><br>
<button onclick="Submit();">Submit</button>
</form>
<form align="center">
<b>Reset</b><br>
<button onclick="Reset();">Reset</button>
</form>
<br><br>
</body>
</html>
One Form should have a button that once clicking it, it will generate a random equation out of 3 saved equations (I'm going to try to write code for a quadratic equation
The Other Form should be where you submit your answer to the random equation that was generated from above. If your answer is correct to the random equation then the background turns green otherwise it turns red. (The second part, I can do on my own)
The Last Form basically reloads your website in the tab.
You just need to write your functions inside the script block (between <script> and </script>, replacing //JavaScript code goes herewith your code.
You have to define the three functions used in the onclick events of the buttons.
ClickMe(), Submit() and Reset()
Defining functions in Javascript
https://www.w3schools.com/js/js_functions.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
Clickme should get a random element from an array
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
Getting a random value from a JavaScript array
Maybe you'll need also some dom manipulation function to add the content of the equation somewhere
https://www.w3schools.com/js/js_htmldom_methods.asp
How to add content to html body using JS?
Submit() needs to get some input and compare it to the expected result, so you'll need some input fields on your submit form
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms
https://www.w3schools.com/html/html_forms.asp
Or you should prompt the user to input the answer
https://www.w3schools.com/jsref/met_win_prompt.asp
https://www.webnots.com/create-alert-prompt-confirm-dialog-boxes-using-javascript/
As you are checking the answer to be valid. You'll need to check evaluating the equation exposed and maybe you need eval but remember
eval is evil
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
Your Reset() function just needs to reload the page
- How to reload a page using JavaScript

How to set file input value when dropping file on page? [duplicate]

This question already has an answer here:
How to set File objects and length property at FileList object where the files are also reflected at FormData object?
(1 answer)
Closed 5 years ago.
I'm attempting to make a control where you can both select a file to submit in the form and drop a file into it to do the same thing. I have something like this where it will also show a preview of the file if it's an image:
<div class="preview-image-container">
<input type="file" name="File" id="File" accept="image/*"
class="image-url form-control" style="display:none;" />
<div class="preview-image-dummy"></div><img class="preview-image-url" />
<div class="preview-image-instruction">
<div class="preview-image-btn-browse btn btn-primary">Select file</div>
<p>or drop it here.</p>
</div>
</div>
Here's a fiddle with MCVE.
The user drops the file in the preview-image-container. The file isn't submitted with AJAX, the user needs to submit the form which contain more data.
For security reasons, we aren't allowed to change the value of the input file with JavaScript. However, I know that the default input file support droppable and there's a bunch of websites that let us select files by dropping them in the form so my guess is that there's a way to do it.
As you can see from the MCVE, I am only interested in using jQuery or pure JavaScript without additional libraries.
Although dropzone.js could be used, it doesn't fit in my requirements and it would require a considerate amount of time to customize its look. Moreover, dropzone.js have certain configuration requirements that can't be met within my ASP.NET application.
There's a similar question but does not have a proper answer: How to set file object into input file in the form in HTML?
Also not similar to drag drop images input file and preview before upload because I have already achieved drag-drop and preview action. My question is specific to the problem of having an empty file input when dropping the file in a parent container.
Disclaimer: Correct as of December 2017 and for modern browsers only.
TL;DR: Yes, now you can!
*if you have a dataTransfer or FileList object
Previously, programmatically changing the files input[type=file] field was disabled due to legacy security vulnerabilities, which are fixed on modern browsers.
The last of the major browsers (Firefox), has recently enabled us to set the files for the input file field. According to testing done by W3C, it seems that you can already do this on Google Chrome!
Relevant screenshot and text quoted from MDN:
You can set as well as get the value of HTMLInputElement.files in all modern browsers.
Source and browser compatibility, see MDN
The Firefox bugfix discussion thread has this demo you can test it out on, and here's the source if you want to edit it. For future reference in case this link dies, I will also include it as a runnable snippet below:
let target = document.documentElement;
let body = document.body;
let fileInput = document.querySelector('input');
target.addEventListener('dragover', (e) => {
e.preventDefault();
body.classList.add('dragging');
});
target.addEventListener('dragleave', () => {
body.classList.remove('dragging');
});
target.addEventListener('drop', (e) => {
e.preventDefault();
body.classList.remove('dragging');
fileInput.files = e.dataTransfer.files;
});
body {
font-family: Roboto, sans-serif;
}
body.dragging::before {
content: "Drop the file(s) anywhere on this page";
position: fixed;
left: 0; width: 100%;
top: 0; height: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.5em;
background-color: rgba(255, 255, 0, .3);
pointer-events: none;
}
button, input {
font-family: inherit;
}
a {
color: blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="https://fonts.googleapis.com/css?family=Roboto:400,400i,700" rel="stylesheet">
<title>JS Bin</title>
</head>
<body>
<h1>Drag and drop files into file input</h1>
<p><small>Supported in WebKit and Blink. To test, drag and drop one or more files from your operating system onto this page.</small></p>
<p>
<input type="file">
</p>
</body>
</html>
Important note:
You can only do this if you have an existing FileList OR dataTransfer object that you are able to set to the input file element (as the setter method DOES NOT accept plain text strings).
For further information, see Kaiido's answer here: How to set File objects and length property at FileList object where the files are also reflected at FormData object?
Now to answer your original question, it should be as simple as this:
document.querySelector('.preview-image-instruction')
.addEventListener('drop', (ev) => {
ev.preventDefault();
document.querySelector('.image-url').files = ev.dataTransfer.files;
});

Using JS to read from a JSON file when button is clicked

I'm trying to solve a problem where a user inputs values into a search box, presses the search button and with the onClick event the search terms are compared to values in a JSON file. Currently I don't know jQuery so if this can be avoided in the solution I would appreciate it! What I have so far is:
<div id="searchb">
<button onclick="userSearch()">Search</button>
</div>
This is a simple div for the search button which calls the userSearch function that deals with the JSON file:
<script>
<!--Function which compares inputted name to names in the .json file. -->
function userSearch(thearr) {
... <!-- All of the code that compares the values -->
console.log();
}
</script>
<script src="filepath on my machine">
</script> <!-- Source path to .json file for script -->
The issue that I'm having is that the function in the onClick event doesn't pass any parameters, because the parameter for userSearch is not defined until the script tag is reached. When I run this 'applet' I get an error saying that the parameter thearr is undefined.
The file path is correct because I used it for a similar problem which automatically generated results from the JSON file on page load, it's the button click that seems to be the problem. Any ideas on how this issue could be fixed would be greatly appreciated! Thanks.
EDIT: Search box HTML as requested
<div id="textboxes">
<textarea id="input1" placeholder="First Name" rows="1" cols="10">
</textarea>
<textarea id="input2" placeholder="Surname" rows="1" cols="10"></textarea>
</div>
From your question, it sounds like you need to get the values from the users input. For userSearch(thearr), i'm not sure what you expect thearr to be. You can get the value of the user input like this:
function userSearch() {
var firstName = document.getElementById("input1").value;
var surName = document.getElementById("input2").value;
console.log(firstName + " " + surName);
}
Note: if you are expecting to process multiple first/surnames, you should rethink the architecture. The logic to do so with the current set up would not be simple to write and more importantly unnecessary.

JS typeerror while checking if null

I am trying to check if fields are blank or not, but it always throws this error:
TypeError: document.getElementById(...) is null
Here is the code: http://pastebin.com/v8mDwG2i
I am using jQuery UI and jQuery. Mine problem is that it always throws null and breaks on that line.
You get that error because in the JS you check for an ID, but in the HTML you have no id tag supplied, only a name tag.
I changed the name="..." for every input-element to id="...".
But there were some other errors in your code as well. Below is a working code snippet with all those error fixed, and an explanation as to what I have changed:
JS, CSS, HTML:
$(window).on('load',function(){
$("#submitBtn").hide();
$("#logStat").hide();
$('#preCheckBtn').click(function(){
$("#logStat").fadeIn(200);
$("#progBar").progressbar();
$("#progBar").progressbar("value", 0);
$("#writeThis").html("Verifying name...");
if ($("#nameIn").val() == (null||"")) {
$("#writeThis").html("ERROR: Name is empty.");
setTimeout(function(){$("#logStat").fadeOut(200);},2000);
return;
}
$("#progBar").progressbar("value", 25);
$("#writeThis").html("Verifying ID...");
if ($("#idIn").val()==(null||"") || isNaN($("#idIn").val())) {
$("#writeThis").html("ERROR: ID is empty or has wrong format.");
setTimeout(function(){$("#logStat").fadeOut(200);},2000);
return;
}
$("#progBar").progressbar("value", 50);
$("#writeThis").html("Verifying phone number...");
if ($("#phoneIn").val()==(null||"") || isNaN($("#phoneIn").val())) {
$("#writeThis").html("ERROR: Phone Number is empty or has wrong format.");
setTimeout(function(){$("#logStat").fadeOut(200);},2000);
return;
}
$("#progBar").progressbar("value", 75);
$("#writeThis").html("Locking data...");
$("#nameIn").attr("disabled", true);
$("#idIn").attr("disabled", true);
$("#phoneIn").attr("disabled", true);
$("#submitBtn").show();
$("#progBar").progressbar("value", 100);
$("#writeThis").html("Done!");
setTimeout(function(){$("#logStat").fadeOut(200);},1000);
});
});
body{
font-family: sans-serif;
width: 1020px;
margin: 25px auto;
}
#logStat{
margin: auto;
text-align: center;
padding: 10px;
width: 60%;
border-radius: 5px;
background-color: #B3B3B3;
}
<link href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.0/jquery-ui.min.js"></script>
<body>
<form action="data/scripts/submit_form.php" method="post">
<input type="text" placeholder="Name" id="nameIn" required /><br />
<input type="text" placeholder="ID" id="idIn" required /><br />
<input type="text" placeholder="Phone number" id="phoneIn" maxlength="10" required /><br />
<input type="submit" value="Run PHP" id="submitBtn" />
</form>
<button id="preCheckBtn">Pre-check data</button>
<div id="logStat">
<div id="progBar"></div>
<p id="writeThis"></p>
</div>
</body>
(fiddle: http://jsfiddle.net/sdbhu7yL/8/)
In the second and third if-clause you only check the input-element itself, not it's value. I think you probably just forgot the .value, so I changed it to check the value.
In those same if-clauses, isNaN(checkData) gives an error because checkData is never declared, it's undefined. I changed it to isNaN($("#someID").val()) to check the value directly.
In all your if-clauses, I changed ==null into ==(null||""). Otherwise, if you click the pre-check-button while one or more of the input fields are still empty, they all get disabled anyway, and you can't fill in the empty fields anymore. (I'm not so sure if disabling them is such a good idea in the first place, because a user might make a mistake filling them in, and then he/she can't correct it anymore.)
I put the CSS and JS in separate files. This is good practice: keep different kinds of code separated. (In the code snippet and jsfiddle they are just in separate sub-windows, but on your actual site you need to link to the CSS and JS files - just like you link to the jQuery '.js' and '.css' files.)
I removed the loaded() function. The whole idea of jQuery's document.ready and window.load is to replace the normal JavaScript's window.onload.
What you are doing is this: on page load you call a function loaded() (from inside your HTML body), and inside that function you check for document.ready. That is very redundant.
Plus, document.ready is called before window.load, so putting document.ready inside the function that is called on load, has no use whatsoever. Actually, the first two .hide() lines weren't even executed; the submitBtn and logStat remained visible, because you checked for document.ready after window.load, but document.ready won't fire anymore because it already happened before window.load.
(I recommend always using window.load btw, unless there is a specific need for document.ready.)
I put window.load around the whole code, not just the first two .hide() lines. This is how window.load should preferably be used.
I removed the type="button" from your pre-check-button in HTML. type="button" is only used on input elements to classify it as a button (because there are more input types). If you already use a dedicated <button> element, you don't need the type="button" anymore.
I gave the pre-check-button an ID and moved the onclick-binding to jQuery: $('#preCheckBtn').click(function(){ ...});. It is cleaner to have all your JS related code inside the JS file. Read about it here.
I translated all your regular JavaScript to jQuery (e.g. document.getElementById("someID").innerHTML = ...; to $('#someID').html(...);.
I added $("#submitBtn").show(); at the end, I think you probably just forgot to add it (I'm assuming you want that button to show when all if-clauses are passed).
I changed your "ERROR: ID is NULL." messages to a more user friendly text, because that NULL-error message also displays when you type in text (instead of numbers), which makes the message incorrect. (This is more of a design issue of course, feel free to hate me for it.)

html span id as javascript function argument

I'm trying to create a copy to clipboard IE javascript function but my code isn't working. How should I format my parameters and pass the argument?
/*invisible storage*/
<textarea id="storageBox" STYLE="display:none;">
</textarea>
<p id="abc">I WANT TO COPY THIS TEXT</p>
<button onClick="Copy(abc);">Copy</button><br />
<script type="text/javascript">
function Copy(txt) {
storageBox.innerText = txt.innerText;
Copied = storageBox.createTextRange();
Copied.execCommand("RemoveFormat");
Copied.execCommand("Copy");
}
</script>
Major karma for anyone who can write this using zclip or show me a similar example as well!!
The following changes should help:
... onclick="Copy('abc');"...
storageBox.value = document.getElementById(txt).innerText
I think. You weren't very specific in saying what doesn't work or even for what reason you're trying to hijack the clipboard (what if the user has important stuff in there?)
First, you need to pass the parameter as a string:
<button onClick="Copy('abc');">Copy</button><br />
In your function, you need to get the element from the DOM based on this ID (as a string):
function Copy(txt) {
storageBox.innerText = document.getElementById(txt).innerText;
...
Though I commented your script working fine, there is something to fix in the HTML. If you set display: none, execCommand() can't copy the content. So you'll need to do this:
<textarea id="storageBox" style="width: 0px; height: 0px; border: 0px;"></textarea>

Categories