Hulk
Hulk

Reputation: 34180

jquery assign value to global variable on click

How to get the scenario_id assigned to the global variable..right now in the console it prints empty string. How to go about this

  var scenario_id = "";
  $('.edit_class').click(function() {

    scenario_id = $(this).attr('value');
  });

  console.log(scenario_id);

Upvotes: 0

Views: 1586

Answers (1)

colestrode
colestrode

Reputation: 10668

The value of scenario_id will only be assigned on a click event. Your console.log() is running after you've assigned the handler but before the user has clicked edit_class, so the value will be undefined. Try this to see the updated value of scenario_id:

var scenario_id = "";
$('.edit_class').click(function() {
    scenario_id = $(this).attr('value');
    console.log(scenario_id);
});

It may help you to read over the answer to this question which explains javascript variable scoping.

Upvotes: 4

Related Questions