titi
titi

Reputation: 1035

Create the global variable in jquery

I tried to get the value of the id of my list using this code :

var ticket = '';
$(".selectedcategory").mouseover(function () {
   ticket = this.id;
});
$("#subCat").remove();
var urlCat = '<%: Url.Content("~/") %>' + "Gallery/TestGallery";
var list = $(".level1").append('<ul ></ul>').find('ul');

$.getJSON(urlCat, { Depid: ticket }, function (dataCat) {
  $.each(dataCat, function (indexCat, dataOptionCat) {
      list.append('<li><a href="teste">' + dataOptionCat.Name + '</a></li>');
});
});

I want to get the id of the ".selectedcategory" is "ticket" to use in "$.getJSON(urlCat, { Depid: ticket }, function (dataCat) {" , but it is undefined when using outside the mouseover() function.

Could anyone tell me how to get this.id outside the mouseover() function please?

Thanks so much.

Upvotes: 0

Views: 139

Answers (2)

Tadeck
Tadeck

Reputation: 137450

What is the problem

By the following code:

$(".selectedcategory").mouseover(function () {
   ticket = this.id;
});

you do not immediately execute ticket = this.id assignement, you only attach event handler for mouseover to the category. Later in the code you are pulling JSON passing empty string within the request params.

How you can solve this and similar problems in your code

Just use event-based programming, by invoking functions only when specific event occurs, and possibly passing callbacks to them. You could learn it by searching the web - one of the resources is here: http://mostlygeek.com/tech/event-driven-programming-with-jquery/ (it is based on the older jQuery, though, so replace .bind(), .live() and .delegate() with proper usage of .on() from the newest jQuery.

Upvotes: 1

jcage
jcage

Reputation: 651

The problem is that at the time getJSON is called, the mouseover function has not been called yet, thus ticket remains undefined.

It's not clear what you are trying to achieve, but since the result of getJSON seems to depend on the ticket, you could call getJSON inside your mouseover function as well.

Upvotes: 1

Related Questions