-3

I have a global variable in javascript

jQuery(document).ready(function() {

   var soft1414;

   $( ".single_variation_wrap" ).on( "show_variation", function ( event, variation ) {

      soft1414 =  $("#pa_soft-cover-1414").val();    
      console.log(soft1414); 
   });
   
    console.log(soft1414);
    var quantity = $('#component_1516789119 .component_content input.qty').val(soft1414);

});

what is wrong with my code?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
lalaland
  • 73
  • 1
  • 2
  • 8
  • Just think about it..... You are waiting for an event to fire, but somehow you think you can read it before it happens. – epascarello Feb 21 '18 at 06:08

3 Answers3

1

First - You need to put all your logic inside the ready function. Now your ready function works after the last console.log because it is asynchronous.

Second - You have also declared function scoped variable with the same name.

jQuery(document).ready(function() {

   var soft1414;

   $( ".single_variation_wrap" ).on( "show_variation", function ( event, variation ) {

      soft1414 =  $("#pa_soft-cover-1414").val();    
      console.log(soft1414); 
   });

});
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

Issue is in this line

var soft1414 = $("#pa_soft-cover-1414").val();

The var keyword makes soft1414 a local variable inside the callback function.

Remove the var keyword and so the line would look like

soft1414 = $("#pa_soft-cover-1414").val();

Also, callback functions are executed asynchronously so console.log outside the callback is executed first and then the value is defined. Whatever you want to do with the variable should be defined inside the callback function block

cdoshi
  • 2,772
  • 1
  • 13
  • 20
0

Your console.log(soft1414);//undefined excute before jQuery(document).ready(function(){}) so value print before set. so you have to need put all logic inside jQuery(document).ready(function(){}); function.

Devraj verma
  • 407
  • 3
  • 14