Automatically assigning a default dynamic value to a dropdown option using Vue.js

I need to set a default selected value for the select option element, but I am facing difficulty in achieving the desired result.

<template>
    <select v-model="tutor_work.start_year">
      <option>{{tutor_work.start_year}}</option>
      <option v-for="year in years" :key="year" :value="year">{{ year }}</option>
    </select>
<template/>
<script>
import axios from 'axios'
export default {
    data() {
        return {
            tutor_work: {
                organization: "",
                start_year: "",
                finish_year: "",
            },
        }        
    },
    mounted() {
        this.getUserData()
    },
    methods: {
        async getUserData() {
            await axios
                .get('api/v1/user/tutor/work/')
                .then(response =>{
                    this.tutor_work = response.data
                })
                .catch(error => {
                    console.log(error)
                })
        }
    },
    computed : {
        years () {
        const year = new Date().getFullYear()
        return Array.from({length: year - 1980}, (value, index) => 1981 + index)
        }
  }
}
</script>

The functionality of the code is correct, but the issue lies with the positioning of the selected value. The selected year (e.g., start_year: 2019) is displayed as the first option instead of being placed after the previous year, such as 2018.

Answer №1

To assign the value of

:selected="tutor_work.start_year"
to a select element:

new Vue({
  el: "#demo",
    data() {
        return {
            tutor_work: {
                organization: "ff",
                start_year: "2010",
                finish_year: "2019",
            },
        }        
    },
    computed : {
      years () {
        const year = new Date().getFullYear()
        return Array.from({length: year - 1980}, (value, index) => 1981 + index)
      }
  }
}
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
    <select v-model="tutor_work.start_year">
      <option v-for="year in years" :key="year" :value="year" :selected="tutor_work.start_year">{{ year }}</option>
    </select>
</div>

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

Issues with connecting to Socket.IO in Cordova app

I'm having troubles setting up my Cordova app to establish a socket.io websocket connection. Despite following the instructions I found, it doesn't seem to connect when running in debug mode. Can anyone help me troubleshoot this issue? Server Si ...

Guide to triggering an API call upon changing the value in a Vue Multiselect component

Is there a way to trigger an API call when the value changes in a Vue Multiselect component? I want to update the value in the multiselect, make an API call, and display the result in the console. Below is my code snippet. <template> <div> ...

Mastering jQuery ajax in Google Chrome Extensions

I have developed a script to fetch data from an external server using JSONP request in jQuery. Please take a look at the code snippet below: $("#submit").click(function() { var state = $("#state").val(); var city = $("#city").val(); $.ajax({ ...

Retrieve the ID of a specific row within a table in a datatables interface by selecting the row and then clicking a button

My goal is to have a table displayed where I can select a row and then have the option to edit or delete that row with a query. To achieve this, I need a primary key that won't be visible to the user. This is how my table is set up: <table id=&apo ...

What is the significance of the colon found within a VueJS/Vuetify/HTML component tag?

Incorporating Vuetify into my project has led me to this VueJS, Vuetify, or HTML inquiry. The component in question displays as follows: <v-list-tile v-for="item in menuItem.items" :key="item.type" :style="`background: ${item.colour}`" :h ...

Merge two distinct arrays of objects based on a shared field

I have two arrays of objects that I need to merge, with the expected output as: [ { "scenario": [ { "errorname": "Error 01", "status": 5, "desc_1" : "test", "desc_2" : "testing" }, ...

Utilize the $scope variable as a JSON object for interacting with the $http service

Is there a way to extract all the data from Angular's scope service without creating an additional object? I am trying to send everything on the scope to a server using $http.post, but it seems that $scope is a circular structure, resulting in "Conver ...

Utilizing jQuery Mobile - Dividing content across multiple HTML files

In the process of developing a web application utilizing jQuery and jQuery mobile, I am aiming to display various pages. Given that the corresponding html-markup may become lengthy, I am interested in dividing the html into separate files. For instance: & ...

Could a potential concurrency issue arise when handling a Queue in JavaScript?

I am faced with a situation where I need to persist an array of properties via AJAX calls to a database. However, the current API does not allow sending the strings in batches, and simple looping will cause overwriting issues. To overcome this, I have impl ...

Convert a negative number to ASCII representation

Currently, I am attempting to extract the longitude and latitude of a user in order to utilize it in a Yahoo API query for obtaining the WOEID based on these coordinates. Subsequently, the WOEID will be passed through to a weather API call. My current pre ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

Next.js - Anticipated that the server HTML would include a corresponding <div> within <div> tag

For a live demonstration, please click here In my current project, I am experimenting with creating a simple layout that adjusts based on the user's screen size. Specifically, on mobile devices, only the latest posts should be displayed. On desktops, ...

Steps for correctly invoking a function based on input value conditions

Lately, I've been developing a new website geared towards serving as a platform for various travel agencies to showcase their tour packages. The homepage features a functional filter section that enables users to search for offers based on different ...

Adding content to a paragraph using Jquery

I have 4 sets of data associated with a click-bind event. My goal is to retrieve the value from a hidden field in each set and display it in a paragraph elsewhere on the page when the corresponding checkbox is clicked. Currently, I'm focused on gettin ...

Ways to initiate JavaScript event upon clearing input form field

I'm working on creating a dynamic search feature. As the user types in the search box, JavaScript is triggered to hide the blog posts (#home) and display search results instead (the specific script for this is not shown below). However, when the user ...

Loading data in advance with vuex and vue-resource

I'm currently in the process of developing an application based on this particular structure: http://vuex.vuejs.org/en/structure.html Within my components/App.vue file, the layout is as follows: <template> <div id="app"> <course :co ...

The Datejs library is experiencing issues following an upgrade to jQuery 3.x

I'm currently working on a node.js project that utilizes the Datejs library. However, after updating our local jQuery file from version 1.9.1 to 3.6.0, this library has stopped functioning properly. Here is a snippet of the code: var today = Date ...

Pinia seems to be failing to refresh and display the latest image

My store and state is updating correctly. I'm currently using Ionic along with vue.js composition using Pinia. After making a selection on a previous route to choose a new image, the image gets updated properly in pinia, but it does not reactively ch ...

Using Selenium in JavaScript to upload an image is a straightforward process

I am trying to automate the process of uploading a picture using Selenium with the following script: driver.findElement(By.id(`avatar-upload`)).sendKeys(`/home/user/Desktop/smg935-0hero-0930.jpeg`) But I keep receiving this error: ElementNotInteractable ...

Mastering Cookies in Javascript

I have been exploring the world of cookies in Javascript and decided to create an experimental log-in page. The page is fully functional, but I am interested in displaying the user's username and password using cookies. Is this possible with Javascrip ...