sam sam - 3 months ago 12
Javascript Question

How to get variable value outside a function IN jquery

I have a variable i assign value to it inside a function now i want to get this value outside of this variable but i get undefined, below is my code. I have select2 on my page whcih i want to populate with some data depend on what users choices are, i allow a user to choose a radio button and i get the value of the radio button to determine which data to display in the select menu. Now after my coding i could alert

var size_data
within the onclick event function but couldn't get this value to the select2 where i need it, any help on this will be appreciated

Note
var size_data
is a global variable and the variable that holds different sizes are also global variable

see my DEMO ON FIDDLE

var uk_size = [{ id: '8', text: '8' },
{ id: '10', text: '10' },
{ id: '12', text: '12' },
];
var us_size = [{ id: '4', text: '4' },
{ id: '6', text: '6' },
{ id: '8', text: '8' },
{ id: '10', text: '10' },
];
var eu_size = [{ id: '34', text: '34' },
{ id: '36', text: '36' },
{ id: '38', text: '38' },
];
var ng_size = [{ id: 'XS', text: 'XS' },
{ id: 'S', text: 'S' },
{ id: 'M', text: 'M' },
];
var size_data = ng_size; //default value;
//alert(ng_size);
$("#size-style input:radio").on('click',function() {
//alert(ng_size);

var size_style ="";
size_style = $(this).val();
if (size_style === "ng-size"){
size_data = ng_size;
}else if(size_style === "uk-size"){
size_data = uk_size;
}else if(size_style === "us-size"){
size_data = us_size;
}else{
size_data = eu_size;
}
alert(size_data);//can alert jquery object here
});



$('select.size-select').select2({
name: 'size',
value: 'S',
data: size_data,
tags: "true",
placeholder: "Select size",
allowClear: true
});

Answer

You can initialize the select2 with default value first and then in radio button click event you can modify its data like below:

https://fiddle.jshell.net/nnaL44ur/4/

$("#size-style input:radio").on('click', function() {
  //alert(ng_size);

  var size_style = "";
  size_style = $(this).val();
  if (size_style === "ng-size") {
    size_data = ng_size;
  } else if (size_style === "uk-size") {
    size_data = uk_size;
  } else if (size_style === "us-size") {
    size_data = us_size;
  } else {
    size_data = eu_size;
  }
  alert(size_data); //can alert jquery object here

  var $select = $('select.size-select');
  var options = $select.data('select2').options.options;
  $select.html('');
  // add new items
  options.data = size_data;
  $select.select2(options);

});

hope it will help you.

Comments