menu

Questions & Answers

Why is a declared variable shows nothing in the console?

My code is the following: HTML

<input type="date" min="2023-01-23" id="date-picker" class="date"> <button id="btn-calc" class="btn" onclick="button()">Calculate</button>

JS

` let dateAdd = document.getElementById("date-picker").value;

function button(){

   console.log(dateAdd);
}`

I want to store a userinput(date) in a variable, so i created the "dateAdd" let, but when i choose a date the console shows an empty row(?)

What is the secret i dont get whit this? Thanks!

A googled after it but nothing.The way i want this to work is when the user pick a date, the choosen date is get logged in to the console. The only way i got this kinda work, when i put the variable inside the button() function. But i can't get the variable outside the function.... i dontgetitpleasesendheeeelp.

Comments:
2023-01-24 23:10:12
try changing your function signature to include the event parameter: function button(e){console.log(dateAdd); use var instead of let. there is probably a scoping issue too
2023-01-24 23:10:12
Move let dateAdd = document.getElementById("date-picker").value; inside the button function
2023-01-24 23:10:12
Inline event handlers like onclick are bad practice. They’re an obsolete, cumbersome, and unintuitive way to listen for events. Always use addEventListener instead.
Answers(0) :