0

I have a function:

$('.fakelink').on('change', function () {
    //date = $(this).val();

    date = '2010-01-24';

});

console.log(date); // Not in console

If console.log (date) is moved outside the function, then the console is empty, it turns out that the date is not passed down the code outside the function.

How to send the date value further down the code from the function?

I just can't beat this script, I didn't work with js at all. I read the recommendations, used the advice, but I could not do anything worthwhile.

Help me, please.

Thank you!

  • 1
    `.on('change'` means the function will run when there is a change event. The `console.log()` right after *cannot* execute afte rthere was a change event. It will always execute before. – VLAZ Jul 31 '21 at 07:27

1 Answers1

0

Your function is running asynchronously.
So when your code runs outside the function, it will run before the date value has been defined. notice that on.('change' is changed to on.('click' in this example:

let date;

// This function is asynchronous
$('.fakelink').on('click', function () {

    date = '2010-01-24';

});

console.log("This is outside the function: " + date); // This runs first
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="#" class="fakelink">Click me</a>