Vasiliy
Vasiliy

Reputation: 103

Updating global variable

I want to update my global variable on click. Basically, all my links have IDs which I want to change my global variable to once clicked. Please see my code below:

var selectedBrand = "";

$(document).on("click", ".style-block a", function(e) {
  e.preventDefault();
  var styleID = $(this).attr("id").replace(/[^0-9]/gi, '');
  var selectedBrand = styleID;
  $('#content').load($(this).attr('href'))
  $(this).reload();
});

$('#brand-list').html(selectedBrand);

So as a result I want to show selected ID within div id="brand-list" (as per my code).

Can you help me, please?

Upvotes: 2

Views: 471

Answers (3)

user786
user786

Reputation: 4374

You don't need to use var again inside child function. replace this var selectedBrand = styleID; to just this selectedBrand = styleID;. Your using var selectedBrand inside on change creates local variable which is local, NOT Global

It should be like this

 var selectedBrand = "";

 $(doem cument).on("click", ".style-block a", function(e) {
 e.preventDefault();
 var styleID = $(this).attr("id").replace(/[^0-9]/gi, '');
 selectedBrand = styleID;
 $('#content').load($(this).attr('href'))
 $(this).reload();
 });

 $('#brand-list').html(selectedBrand);

Upvotes: 0

rrk
rrk

Reputation: 15875

When you use var in the child function you are creating a local variable, for the inner function. That is why the global variable was not being updated. selectedBrand = styleID; is enough inside the inner function.

var selectedBrand = "";

$(document).on("click", ".style-block a", function(e){ 
    e.preventDefault();
    var styleID = $(this).attr("id").replace(/[^0-9]/gi, '');
    selectedBrand = styleID;
    $('#content').load($(this).attr('href'))
    $(this).reload();   
});

$('#brand-list').html(selectedBrand);

Upvotes: 1

Tushar
Tushar

Reputation: 87233

Remove var from the selectedBrand inside the event handler. By removing var, the variable selectedBrand is searched in the scope-chain until it is finally found on the Global object.

When you add var to a variable inside function the variable is function scoped i.e. cannot be accessed from outside of that function.

var selectedBrand = "";

$(document).on("click", ".style-block a", function(e) {
  e.preventDefault();
  var styleID = $(this).attr("id").replace(/[^0-9]/gi, '');

  selectedBrand = styleID; // Remove var from here

  $('#content').load($(this).attr('href'))
  $(this).reload();
});

$('#brand-list').html(selectedBrand);

Or, you can also use

window.selectedBrand = styleID;

to update the value of global variable explicitly.

Upvotes: 1

Related Questions