Using VueJS to Create a Range of Years from 1900 to Present Year

I'm currently developing a registration form using VueJS, wherein users need to input their date of birth.

My challenge is in generating a list of years starting from 1900 up to the current year within a <select> element. Any suggestions on how I can accomplish this?

I attempted the following:

new Vue({
  el: '.container',
  methods: {
    getCurrentYear() {
      return new Date().getFullYear();
    }
  }
});
<div class="container">
  <select id="dob">
    <option value="0">Year:</option>
    <option v-for="year in getCurrentYear()" :value="year">{{ year }}</option>
  </select>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

However, the year range always starts from 1. How can I modify the loop within the <option> to begin from the year 1900?

Answer №1

  1. It's best practice to avoid using a method within a loop; instead, utilize a computed property.
  2. Avoid using v-if inside a v-for loop. This can lead to performance issues. Learn more here!

new Vue ({
  el: '.container',
  computed : {
    years () {
      const year = new Date().getFullYear()
      return Array.from({length: year - 1900}, (value, index) => 1901 + index)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div class="container">
<select id="dob">
  <option value="0">Year:</option>
  <option v-for="year in years" :value="year">{{ year }}</option>
</select>
</div>

Answer №2

   initialized(){
this.initializeYears();          
},
     computed : {
           initializeYears() {
      let yearList = [];
      for (var i = 2001; i <= new Date().getFullYear(); i++) {
        yearList.push(i );
      }

      this.yearList = yearList;
    },

    <select2 v-model="form.year">
              <option value="">----</option>
              <option :value="year" v-for="year in yearList" :key="year">
                {{ year }}
              </option>
            </select2>

Answer №3

To filter options based on a condition, you can utilize the v-if directive:

  <option v-for="year in getCurrentYear()" v-if="year >= 1900" :value="year">{{ year }}</option>

[Link: https://v2.vuejs.org/v2/guide/list.html#v-for-with-v-if]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tracking a razor ajax form using pace.js has never been easier with these simple steps

I'm currently exploring the use of pace.js with my Razor ajax form. The form generates a Partial View upon submission. Pace.js, as per its documentation, automatically monitors all ajax requests lasting longer than 500ms without any additional configu ...

Is there a way for me to detect if the user has manipulated the CSS or JavaScript in order to alter the look of my website?

Is there a way to determine if someone is utilizing script or CSS extension tools? For instance, if they have adjusted alignments, applied display: none; to multiple elements, or utilized jQuery's .hasClass to manipulate divs. ...

Can I access the component attributes in Vuetify using Typescript?

For example, within a v-data-table component, the headers object contains a specific structure in the API: https://i.stack.imgur.com/4m8WA.png Is there a way to access this headers type in Typescript for reusability? Or do I have to define my own interfac ...

Access previous value in Vuejs onchange event

In the code snippet below, how can I retrieve the previous value of the model that has been changed, specifically the age in vuejs? var app = new Vue({ el:"#table1", data:{ items:[{name:'long name One',age:21},{name:'long name Two&a ...

Understanding how events propagate in three.js

I am currently working on a scene that consists of multiple objects. To manipulate the selected object, I am using an orthographic camera controller. Specifically, I want to rotate the object with the mouse by pressing shiftKey + 1 (rotation around its own ...

Unattaching Events in AngularJS

I'm still navigating my way through the realms of Angular and MVC programming, uncertain if I'm on the right track. There's a jQuery snippet that I wish to implement in some of my partials, but not all. With event listeners that persist eve ...

Encountering permission issues while attempting to add `@nuxtjs/sentry` in a Docker container running Node 16.14. Installation

While attempting to add @nuxtjs/sentry to my project by running npm install @nuxtjs/sentry, I encountered some issues. Here is the error message I received: npm ERR! code 1 npm ERR! path /app/node_modules/@sentry/cli npm ERR! command failed npm ERR! comm ...

Utilize React Hook Form to easily reset the value of an MUI Select component

I created a dropdown menu where users can select from "Item 1", "Item 2", and "Item 3". Additionally, there is a "Reset" button that allows users to clear their selection and make a new one. Below is the code I used: import React from ...

Tips for creating an endless scrolling/loader feature in Nuxt?

Hey there! I am looking to display data after implementing infinite loading. The data is sent asynchronously using asyncData to the page with an ID. Page <script> export default { async asyncData({ $axios, store }) { const customerId = store.g ...

Encountering a problem with React router

Hello, I'm currently facing some issues with setting up routes in my project. Below is the code snippet from my route.js file: import React, { Component } from 'react'; import Home from './Home'; import Add from './Add' ...

The loop feature in Swiper.js seems to be malfunctioning and not functioning as

I'm currently in the process of setting up a carousel using swiper.js and here is my setup: { slidesPerView: 1, slidesPerColumn: 1, initialSlide: this.initialSlide, loop: true } As expected, I'm encountering an issue where dupl ...

Utilizing JavaScript to conceal div elements within a ul container

How can I hide specific div tags inside a ul tag using JavaScript? All div tags are currently getting hidden when I use the id of the ul tag. However, I need only the first div tag to be shown and the rest to be hidden. Here is the HTML code: <ul clas ...

Restore font-weight if a different list item is chosen

I previously inquired about setting the font-weight to bold on a text element when selected. Thanks to @Eric, this has been successfully implemented! However, I am facing an issue where clicking on one text makes it bold, and then clicking on another text ...

Tips for stopping Infinite Scroll from loading pages when the tab is inactive

I'm currently developing a website using Bootstrap 4 and jQuery, which consists of 3 tabs, each containing masonry elements loaded on scroll with the Infinite Scroll plugin. I'm trying to figure out a way for the Infinite Scroll to only load cont ...

What could be the reason behind receiving a 406 Not Acceptable status at the client side from the server, and why is my Spring controller not being triggered?

Here is the code for an AJAX GET request: $("#tabsss2").click(function tab1() { $.ajax({ type: "get", traditional: true, dataType: 'json', url: "DataGridServlet.htm", cache: false, ...

What causes my input field to lose focus in React.js after typing just one character?

My react.js component is experiencing an issue where the input field loses focus whenever a character is typed. To continue typing or editing, I have to click on the input field again. What could be causing this problem? Below is the code snippet in quest ...

Unable to modify the content of a table cell after triggering a Bootstrap modal event

Looking to update values in rows of a table? Here is an example table: https://i.sstatic.net/6l4f3.png I need to update the title per selected row. After selecting the first row, changing the value works fine. However, when I choose the second row, the ...

AngularJS - Showcase a dynamic list of information according to the value chosen

Seeking assistance from anyone willing. I have data in JSON format structured like this { state1: [ member1, member2], state2: [ member3,member4...], ... } There is a dropdown that displays the states listed in the JSON data. When a state is selected, I ...

Passing an array of items as a property to a child component in React with Typescript is not possible

In my project, I have multiple classes designed with create-react-app. I am trying to send an array of objects to child components as illustrated below. Items.tsx import * as React from 'react'; import ItemTable from './ItemTable'; imp ...

Error: The 'price' property is undefined and cannot be read at path C:NODEJS-COMPLETE-GUIDEcontrollersshop.js on line 45, character 37

I have been attempting to add my products to the cart and calculate the totalPrice, but I keep encountering an error. Here is the error message:- enter image description here. Below is the code from my shop.js file:- exports.postCart = (req, res, next) =&g ...