0

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);
Hulk
  • 32,860
  • 62
  • 144
  • 215
  • it should print an empty string not undefined – Arun P Johny Aug 06 '13 at 12:02
  • 1
    it is because the value of `scenario_id` is changed only after an `edit_class` is clicked. you are logging it before the value is changed. you need to move the console stmt to the callback method – Arun P Johny Aug 06 '13 at 12:03

1 Answers1

4

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.

Community
  • 1
  • 1
cfs
  • 10,610
  • 3
  • 30
  • 43
  • 1
    But i want to assign it to global variable not in the function scope – Hulk Aug 06 '13 at 12:05
  • By defining the variable in the global scope it will be global, regardless of where you set the value. – cfs Aug 06 '13 at 12:05