I have a list of link , when I click on it , I want to count the elements that contain in my list. This is what I coded:
$('a#' + dataOption.ID).click(function () {
$.getJSON("ProductListing/Index", data, function (product) {
$.each(product.ja, function (index, value) {
num_obj = product.ja.length;
});
});
});
alert(num_obj);
The alert is Undefined.
The JSON result is :
{"ja":
[
{"Name":"ABC1","PictureName1":"my image name1","ID":1},
{"Name":"ABC2","PictureName2":"my image name2","ID":2}
]}
Could anyone tell me, how can I count that JSON in my click event. Thans so much.
The code you’ve posted creates a click handler and then immediately does an
alert(num_obj)– given thatnum_objisn’t declared anywhere and the click event itself hasn’t happened yet,num_objis supposed to be undefined at that point.Try moving the alert into the callback of the
$.getJSON()function, to just after the first point wherenum_objactually has a value assigned:Note that I’ve removed the
$.each()since it doesn’t make sense to iterate over theproduct.jaarray and testproduct.ja.lengthfor each element (the fact that you didn’t usethisorindexorvalueinside the$.each()was also a clue that you didn’t need the each).