I’ve no clue what should I add or change in my code. This program is considered to output ‘correct’ when you text in current year ‘2023’ but I don’t get any errors or anything else. It just doesn’t work.
P.S it outputs ‘incorrect’ even if it’s true
const date = new Date();
const input = document.querySelector('.js-input').value;
const button = document.querySelector('.js-button');
const body = document.querySelector('body');
button.addEventListener('click', yearfunc);
function yearfunc(event) {
if (input == date.getFullYear()) {
const div = document.createElement('div');
button.insertAdjacentElement('afterend', div);
div.innerText = 'Correct';
} else {
const div = document.createElement('div');
button.insertAdjacentElement('afterend', div);
div.innerText = 'Incorrect';
}
event.preventDefault();
}
<p>What the year is it right now?</p><br><br>
<input type="text" class="js-input">
<button class="js-button">Send</button>
3
Answers
The difference is that you assigned ‘.value’ too early in the code.
Assigning it directly in the function and comparing using a new variable solves the problem, try this out:
you Are retrieving the input outside of event so when the event actually occurs you are just comparing a pre-loaded value of "". Solution is to fetch the input data inside event handler:
This code should work. The way value was being taken from the ‘js-input’ class, was not giving the correct input value.