问题
I'm relatively new to javascript and jquery. Right now I have a list of words in a txt file. I store this list in an array, and I want to compare the contents of that array to some user input. If there's a match, that specific word should be displayed.
I also use Jasny Bootstrap to perform some typeahead functions to predict which words the user would like to search for.
In the current stage, my function finds matches on the first input character. When using more characters the function returns that no match has been found. Why is that?
Here's my HTML:
<div class="container">
<div class="appwrapper">
<div class="content">
<h3>OpenTaal Woordenboek</h3>
<p>Voer uw zoekopdracht in:<p>
<p><input name="searchinput" id="searchinput" data-provide="typeahead" type="text" placeholder="Zoeken...">
<p class="dict"></p>
</div>
</div>
</div> <!-- /container -->
And here's the jQuery:
<script src="bootstrap/js/jquery.js"></script>
<script src="bootstrap/js/bootstrap-typeahead.js"></script>
<script type="text/javascript">
var data;
var myArray = [];
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "OpenTaal-210G-basis-gekeurd.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
data = txtFile.responseText.split("\n"); // Will separate each line into an array
myArray = [data];
} //"\r\n"
}
}
//console.write(data);
searchinput.onkeypress = function() {
//alert("The function is working!");
var formInput = document.getElementById("searchinput").value;
if (myArray == formInput) {
alert("There's a match!");
$('.dict').append('<div class="result">' + myArray + '</div>')
} else {
alert("No match has been found..");
}
};
回答1:
You didn't use jquery, just native javascript.
After your script reading file, just do:
$(searchinput).on("keypress", function() {
if ($.inArray(formInput,myArray) > -1) {
alert("There's a match!");
}
});
UPDATE
$(searchinput).on("blur", function() {
if ($.inArray(formInput,myArray) > -1) {
alert("There's a match!");
}
});
回答2:
You need to search the entire array, not just compare it to the value:
if ($.inArray(formInput,myArray)>=0) { // returns -1 if no match
alert("There's a match!");
http://api.jquery.com/jQuery.inArray/
回答3:
Loop through the array and match the input value with array elements like :
for(var i in myArray) {
var arrayElement = myArray[i];
if (arrayElement == formInput) {
//Do your stuff
}
}
来源:https://stackoverflow.com/questions/18965260/javascript-jquery-compare-input-value-to-array