I have the following search function:
function filter() {
$("table#list tr").each(function () {
var search = $("#search").val();
var name = $(this).find("span.name").html();
var email = $(this).find("span.email").html();
var ref = $(this).find("span.reference").html();
var match = false;
var count = 0;
if((name != undefined) && (email != undefined) && (ref != undefined)) {
if(name.indexOf(search) >= 0) match = true;
if(email.indexOf(search) >= 0) match = true;
if(ref.indexOf(search) >= 0) match = true;
if(match) {
$(this).removeClass("collapse");
count++;
} else {
$(this).addClass("collapse");
}
}
});
$("#result-count").html(count + " results found.");
}
However on the last line, count
is undefined, because I created it inside the function. How can I get the value outside of the $.each function?
Edit: I also just realized I'm resetting the count inside the loop so it will always = 0! How can I count the results properly?
Declare count
outside the each
block. Also note that you can tidy up the logic a little too:
var count = 0;
$("table#list tr").each(function () {
var search = $("#search").val();
var name = $(this).find("span.name").html();
var email = $(this).find("span.email").html();
var ref = $(this).find("span.reference").html();
if (name == undefined || email == undefined || ref == undefined)
return;
if (name.indexOf(search) >= 0 || email.indexOf(search) >= 0 || ref.indexOf(search) >= 0) {
$(this).removeClass("collapse");
count++;
} else {
$(this).addClass("collapse");
}
});
$("#result-count").html(count + " results found.");
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments