0

I'm trying to make my code dependent on certain variables by changing them with a select. Is it possible to access the result outside of the function in jQuery?

js

function myCalendar(){    
  //global variable 
  var thismonth = '';
  //onchange get selected month
  $(document).on('change','#select_month',function(){
    thismonth = $(this).val();
  });

  //check if empty
  if(thismonth !==''){//always return empty?
    var mm = thismonth;
  }else{
    var mm = new Date().getMonth();
  }
}
alexP
  • 3,672
  • 7
  • 27
  • 36
Grogu
  • 2,097
  • 15
  • 36
  • post html code also – prasanth Jan 18 '21 at 07:32
  • The place in the code where you've said you want to use the value is reached before the change event occurs, and not revisited later when the change event occurs. Trigger the code you want to run from the change handler, since that is run when the change event occurs. (Code triggered from other event handlers will also see updates to that variable.) – T.J. Crowder Jan 18 '21 at 07:34
  • @T.J.Crowder: Mind you the codes you see are only samples. It would make sense to do it inside the event handler if it was just this small piece but I have many more codes that depend on that event. Putting 200 lines of codes inside an event handler wouldn't make any sense at all. I'm not a pro at jQuery and Javascript yet but I know enough. It truly needs to be handled outside. I'm going to handle it with a callback as suggested. Thanks! – Grogu Jan 18 '21 at 17:19
  • @Grogu - What you do is break up those 200 lines of code into appropriately-sized functions, and call those functions as appropriate in your code (for instance, from your event handler). – T.J. Crowder Jan 18 '21 at 17:21
  • @T.J.Crowder: You're right. I'm probably going to have to restructure my entire logic. Another all nighter let's gooo haha! – Grogu Jan 18 '21 at 17:35

0 Answers0