skip to Main Content

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);

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search