I am trying to build a search box that searches my site for text. Right now I am trying to create a jquery keyup() function that takes input from my search box and compares it to text within two divs. This code does not seem to be working the way I intend it when I type the div's text contents Tom or Randy into the search input. The result is console.log("nothing").
My Html
<input type="text" id="searchfor">
<div class ="name"> Tom </div>
<div class ="name"> Randy </div>
My jquery
$(document).ready(function(){
$('#searchfor').keyup(function(){
$(".name").each(function(){
var $divText = $(".name").text().trim().toLowerCase();
var $searchInput = $("#searchfor").val().trim().toLowerCase();
if($searchInput === $divText) {
console.log("something");
}else{
console.log("nothing");
}
});
});
});
I want to know how I can get $searchInput to equal $divText so that when someone types Randy into the search input field the function will console.log("something"). Thank You
The problem is var $divText = $(".name").text();
will combine text of all the collection of elements.
Within your each
you want the specific instance so use $(this)
.
$('#searchfor').keyup(function() {
// no need to get value in each iteration of loop...just store it here once
var $searchInput = $(this).val().trim().toLowerCase();
// within loop `this` is instance of div.name
$(".name").each(function() {
var $divText = $(this).text().trim().toLowerCase();
if ($searchInput === $divText) {
console.log("something");
} else {
console.log("nothing");
}
});
});
This will only match if whole name is typed in.
If you only want partial match use indexOf()