0

Is it possible to print the current year inside an input value with javascript? PS.: I don't want to use the type="date" method. PS. 2: The value needs to be printed on the input as soon as the screen is opened.

var dateControl = document.querySelector('input.year[type="text"]');
dateControl.value = "getFullYear()";
<input type="text" id="year" value="">  
Mari
  • 85
  • 7
  • 1
    The linked duplicate shows you how to get the year. Aside from that, your selector should simply be: `document.querySelector('#year')` since you can select on an `id`. – David Dec 27 '21 at 18:49
  • Unfortunately this solution doesn't work for me, as I've already tried it. – Mari Dec 27 '21 at 18:50
  • Can you update the code shown to demonstrate that attempt and indicate what specifically isn't working? – David Dec 27 '21 at 18:50
  • Well, the published code should have the current year already printed inside the input and it does not appear. – Mari Dec 27 '21 at 18:52
  • 1
    try ` dateControl.value = new Date().getFullYear(); ` – Himanshu Jangid Dec 27 '21 at 18:53
  • Do you want to show just the year of whatever the date was put in the field? – Zlatko Dec 27 '21 at 18:53
  • @Mari: Look at the linked duplicate again, and look at your code in the question above again. Specifically the part where you use the string `"getFullYear()"` and where the linked duplicate uses the code `new Date().getFullYear()`. Do you see the difference between those two things? – David Dec 27 '21 at 18:53
  • @Zlatko I want to show the current year, but the person can change if necessary. – Mari Dec 27 '21 at 18:55
  • 1
    @Mari: In short, when applying the information present in the linked duplicate, what happens when you just do this?: `document.getElementById('year').value = new Date().getFullYear();` – David Dec 27 '21 at 18:55
  • It worked! The problem was the fact in document.getElementById('year'). Thank you. – Mari Dec 27 '21 at 18:59

0 Answers0