I have on my html two inputs (text and button) for the user to type and submit:
<input type="text" id="userInput">
<input type="button" value="Submit" onclick="search()">
And I'm storing this input inside a variable:
var userInput
function search(){
userInput = document.getElementById("userInput").value
userInput = userInput.toString().toLowerCase()
}
I'm getting the full string that I want to search inside from a jQuery.get and storing it on a variable called data:
var data
$.get("foo.txt", function(response) {
data = response
});
And then I'm using a if condition to do stuff based on If I could find the userInput inside the String from the .txt file (stored in the data variable) or not:
if (data.includes(userInput) == true) {
console.log('found it!')
} else {
console.log('nah')
}
But my data variable is getting undefined... I'm guessing it is because it gets a value inside the $.get. I'm new to JS, can't figure out how to make this work. Anyone can help me?
Note: I can log the data variable and see the text file content inside of it.
Full code:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="userInput">
<input type="button" value="Submit" onclick="search()">
<script>
var userInput
function search(){
userInput = document.getElementById("userInput").value
userInput = userInput.toString().toLowerCase()
}
var data
$.get("foo.txt", function(response) {
data = response
});
if (data.includes(userInput) == true) {
console.log('found it!')
} else {
console.log('nah')
}
</script>
</body>
</html>
Is this because of: "var is function-scoped, meaning that variables instantiated with the keyword would only be accessible to code within the function", right?
Can anyone help me find a solution for that?