How to use year input type in HTML?



Use the placeholder attribute to let the user know that the required input format is YYYY, and the <input type="number">, min, and max attributes to limit the range of possibilities. To the first argument of a new Date, pass the value or valueAsNumber during the input event ()

Following are the examples…

Example

In the following example we are using placeholder to mention that the input type is year.

<!DOCTYPE html> <html> <body> <input type="number" placeholder="YYYY" min="1999" max="2020"> <script> document.querySelector("input[type=number]") .oninput = e => console.log(new Date(e.target.valueAsNumber, 0, 1)) </script> </body> </html>

Output

On executing the above script, it will generate an input type of year added using a placeholder.

Example: Using JQuery datepicker tag

To use year input type, we will be using jQuery to add datepicker. It is used with the text input type. On running the program, only the year will be visible.

You can try to run the following code to learn how to use input type to set a year −

<html> <head> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(function() { $( "#date" ).datepicker({dateFormat: 'yy'}); }); </script> </head> <body> <form action = "" method = "get"> Details:<br> <br> Student Name <br> <input type="name" name="sname"> <br> Year of Birth <br> <input type="text" id="date"> <br> <input type="submit" value="Submit"> </form> </body> </html>

Output

On executing the above script, it will generate a text input type of year added using the datepicker JQuery.


Advertisements