I'm working on a jquery where user selects a category and then a range of years.
my problem is I'm getting cats is not defined
although it is, and I can see it using alert(cats);
from $('[id^="multi-"]').click(function () {
but when i'm choosing the range of years, from $("#multi_select_wrapper").keyup(function(){
"cats" variable is not defined
$('[id^="multi-"]').click(function () {
$(this).toggleClass('selected');
var cats = [];
$(".selected").each(function(){
cats.push($(this).attr('data-id'));
});
var cats = cats.join(",");
alert(cats);
});
$("#multi_select_wrapper").keyup(function(){
if(f_year!==null && t_year!==null){
var years = [];
var counter = parseInt(t_year)+1;
for (var i = f_year; i < counter; i++) {
years.push(i);
}
alert(years);
alert(cats);
}
$("#multi_search").attr("href", "index.php?do=m&msc=" + cats + "&msy=" + years);
});
cats
is only declared inside your click handler function and is not given a value until that click handler runs. It's value is only available inside that function.
If you want cats
available outside that function, then you must declare cats
at a higher scope (e.g. perhaps as a global variable or some higher scope). Then, it's value could be used anytime AFTER the click handler function runs.
In addition, you shouldn't be declaring the cats
variable twice in your click handler. This won't cause an error, but it is incorrect. Declare it with var
only once per scope.