Home > Blockchain >  Use variable outside the function
Use variable outside the function

Time:11-04

To double-check, I try a console log both inside and outside the function.

The one inside the function is fine, but the one outside the function displays "undefined."

I need to get the value of startDate and use it outside the function.

I tried every suggestion here, but none of them worked. https://bobbyhadz.com/blog/javascript-select-onchange-get-value

here is the code:

var startDate;
        
$('#dayFrom, #timeFrom').change(function() {
   startDate = $('#dayFrom').val()   ' '   $('#timeFrom').val();
   console.log("inside start date: "   startDate);
});

console.log("outside start date: "   startDate);

CodePudding user response:

Did you try the arrow function? You can change code to this:

var startDate;
    
$('#dayFrom, #timeFrom').change(() => {
startDate = $('#dayFrom').val()   ' '   $('#timeFrom').val();
console.log("inside start date: "   startDate);
});

console.log("outside start date: "   startDate);

when you use the function keyword to create a function you enter in very complex area and you can avoid that area by simply using the arrow function like this.

CodePudding user response:

The startDate variable has already changed when the event listener runs. It is undefined because you are printing the value of it before the change event listener runs.

  • Related