0

I am currently learning Javascript. I'm working on a program with FileReader.

How can I access variable file for variable perf?

My code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style/style.css">
<title>FileReader</title>
</head>
<body>
<h1>FileReader</h1>
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
Input: <input type="text" id="qi" value="">
<br></br>
<button onclick="check()" class="button buttonB">Check</button>
<p id="ans"></p>
<p id=".same"></p>
<script src="main.js"></script>
</body>
</html>



function check(){
  var text = document.getElementById("qi").value;
  console.log(`Text: ${text}`);

  var perf;       //The value should be `file`

  if (text === perf){
      console.log("Same");
      document.getElementById(".same").innerHTML = "Same";
  } else{
      console.log("Not Same!!!")
      document.getElementById(".same").innerHTML = "Not Same!!!";
  }
}

function openFile(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var file = reader.result;
console.log(file);
document.getElementById("ans").innerHTML = file;
};
reader.readAsText(input.files[0]);
};
  • No problem. You need to be more specific with your question. I see some issues with your code. In line 4 you declare `perf`, then in line 5 you check if it's the same as `text`variable but `perf` is undefined - you never initialized it, so the `else` condition will never occur. Then this part `document.getElementById(".same")` --> `.same` ? is it really an id you put on the element or is it a class? If it's a class you should use `document.querySelector(".same")`; Another thing is that most of your code is in the `check()` and `openFile()` functions but you never execute them. – codeepic Oct 17 '18 at 21:23
  • The functions are called by buttons. Html code:` FileReader

    FileReader


    Input:

    `
    –  Oct 18 '18 at 08:31
  • Actually my dupe was wrong, sorry. Here is a simple closure issue: you need to declare either `file` or `perf` or a third variable in the scope shared by both your functions (here that would be the global scope), so that you can set it in one of your func and get it in the other (`var shared; function check(){...var perf = shared;...} function openFile(){... shared = reader.result; ...}`) – Kaiido Oct 18 '18 at 08:50

1 Answers1

-1

Method 1 : Compare the innerHTML you saved

var perf = document.getElementById("ans").innerHTML;

Method 2 : Save the variable in a global scope

Just save the variable file in the global scope :

Replace

var file = reader.result;

By

window.file = reader.result;

And

if (text === perf){

By

if (text === window.file){
blue112
  • 52,634
  • 3
  • 45
  • 54