[Solved] how to get value outside jquery click function


the second alert(projectId); outside the “click” event handler runs as soon as the page loads. Inevitably this is before your “click” handler can possibly be executed, because the user has likely not had time to click on it, and even if they had time, there’s no guarantee that they will. Therefore the variable projectId is not populated when that code executes.

You can certainly use projectId outside your “click” event, but you have to wait until after at least one “click” event has happened before you can expect it to have a value.

There’s also danger that your hyperlinks are causing the page to postback before any of this ever happens. Since you’re using jQuery you can prevent this very easily:

$('body').on('click', '#list a', function(event) {
  event.preventDefault(); //prevent default hyperlink redirect/reload behaviour
  projectId=this.id; //id should = 30
  alert(projectId);  //here display 30
});

Lastly, ensure that this other place you want to use the value is not doing anything silly like declaring another “projectId” variable with narrower scope and then trying to use that. For example, this will not work as you wish:

var projectId = null;

$('body').on('click', '#list a', function(event) {
  event.preventDefault(); //prevent default hyperlink redirect/reload behaviour
  projectId=this.id; //id should = 30
  alert(projectId);  //here display 30
  exampleFunc(); //call the function below
});

function exampleFunc() {
  var projectId = null; //oops, another "projectId" with narrower scope (within this function) will take precedence here
  alert(projectId); //will be null
});

Whereas this will:

var projectId = null;

$('body').on('click', '#list a', function(event) {
  event.preventDefault(); //prevent default hyperlink redirect/reload behaviour
  projectId=this.id; //id should = 30
  alert(projectId);  //here display 30
  exampleFunc(); //call the function below
});
function exampleFunc() {
  alert(projectId); //will be 30
}

solved how to get value outside jquery click function