Ensure the initial value in the dropdown menu is automatically set to the first value in VueJs

How can I set the first value of my time object as the default value for my dropdown in Vue? I want the first value to be pre-selected when a user enters the website, but currently only display the value without actually selecting it.

time Object:-

{ "1290_1320":"21:30 - 22:00",
  "1320_1350":"22:00 - 22:30",
  "1350_1380":"22:30 - 23:00"
}

Dropdown HTML:-

<div class="form-group col-md-8">
   <select id="pickup" class="form-control" @change.prevent="changeTime($event)">
      <option selected="selected" v-for="(time, i) in this.timeslots" :key="i" 
       :value="time">{{time}}</option>
   </select>
</div>

Vue:-

export default {
  data() {
    return {
      selectedTime: null
    }
  },
  methods: {
     changeTime(event) {
       this.selectedTime = event.target.options[event.target.options.selectedIndex].text;
  }

Dropdown javascript:-

// remove "selected" from any options that might already be selected
$('#pickup option[selected="selected"]').each(
    function() {
        $(this).removeAttr('selected');
    }
);

// mark the first option as selected
$("#pickup option:first").attr('selected','selected');

Answer №1

For your specific scenario, the following approach can be taken:

<div class="form-group col-md-8">
   <select id="pickup" v-model="selectedTime" class="form-control">
      <option v-for="(timeValue, timeID) in timeslots" :key="timeID" :value="timeID">{{ timeValue }}</option>
   </select>
</div>
<script>
import axios from 'axios';

export default
{
  name: 'MyDropDown',
  data() 
  {
    return {
      selectedTime: null,
      timeSlots: {},
    }
  },
  created()
  {
    this.fetchData();
  },
  methods: 
  {
    fetchData()
    {
      axios.get('/api/getTimeSlots').then(response =>
      {
        this.timeSlots = response.data;
        this.selectedTime = Object.keys(response.data)[0];
      });
    },
  }
}

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

Image uploading in Angular is not compatible with Internet Explorer, however, it functions correctly in Google Chrome

As of now, my implementation has been successful in all browsers except for Internet Explorer 11. Despite being able to successfully upload .jpeg, .jpg, and .png images in Google Chrome, I am facing issues when trying to upload them in IE 11. The code wo ...

Webpack encounters an error while attempting to load Bootstrap v4.0.0-beta

I've encountered an issue with my webpack configuration and Bootstrap v4.0.0-alpha.6 that was working fine until I attempted to switch to v4 beta. Unfortunately, I can't seem to get it working properly now :( Here is a snippet of my config: w ...

Turning off the transpiler in Vue Webpack to simplify the debugging process

Debugging in Vue can be quite challenging, especially when it comes to setting breakpoints and stepping through the code. The issue seems to stem from the transpiling of javascript ES6/ES2015/ES2016/ES2017 to ES5. While source maps provide some assistance, ...

Transferring a JavaScript element's ID to PHP

Recently, I came across a JavaScript function that automatically updates the date and time for me. I found the script on this URL: http://jsfiddle.net/pLsgJ/1/ setInterval(function() { var currentTime = new Date ( ); var currentHours = curren ...

Error message: Unable to locate the 'npm' task in Visual Studio Code

When attempting to execute a JavaScript or Python file in VS Code, an error message consistently pops up: Even after reinstalling node, the issue persists. Clicking on configure reveals various options, each leading me to a json file. New to coding, I ma ...

Error encountered in the main thread: Fail to click on element at current position

An error occurred in thread "main" org.openqa.selenium.WebDriverException: The element located at point (126, 7.98333740234375) is not clickable. Another element is intercepting the click: <div class="_1H5F__" data-reactid="10"></div> The com ...

Bootstrap 4's Img-fluid class fails to properly resize images

Having a bit of trouble with my navbar setup. I want to use an image brand with img-fluid so it resizes to fit the div and remains responsive. However, instead of resizing, the image just stretches out the navbar making it huge. Here's my code: ...

Having trouble scrolling to the top in Flickr Search using AngularJS, the results are restricting my movement

I recently followed a tutorial on creating a Flickr Search App with AngularJS (https://www.youtube.com/watch?v=lvGAgul5QT4). I managed to show the search results on my page, but encountered an issue: I couldn't scroll all the way back up to the search ...

Issue with Material Table not refreshing data after mutation occurs

Whenever a user includes more details, a mutation is performed in the database to add the new information. Subsequently, the local state is updated to include the new data in the lead. Although my mutation and state update successfully, there seems to be ...

Is there a way to restrict the date-picker in vue to only allow Mondays?

Is there a way to customize the v-data-picker component in my Vue project so that only Mondays are allowed to display, with all other days being disabled? Here is the code I currently have: <template> <v-row justify="center"> & ...

Ensure that the extension is only loaded once Angular has fully loaded

I am currently working on a Chrome extension that incorporates event listeners to elements within a page utilizing Angular 1.2.10. The following code snippet is an example of what I have: window.addEventListener("load", (event) => { var switchButton = ...

The Storybook compilation consistently encounters errors

Check out my repository here: https://github.com/zapify-ui/zapify I'm facing an issue with building Storybook using the command: npm run build-storybook How can I identify the specific error or debug it effectively? The error thrown is: (node:46619) ...

Opening a modal in React Material UI from an autocomplete component results in losing focus

My current challenge involves utilizing the material-ui library to create an autocomplete feature where each item is clickable and opens a modal window. The basic structure looks like this: const ModalBtn = () => { ... return ( <> ...

I pressed the button but the globalCompositeOperation isn't working as expected. How can I make it function correctly to achieve the desired output like the second canvas?

<!DOCTYPE html> <html> <head> <title>Canvas Compositing Tutorial</title> </head> <body> <canvas id="myCanvas" width="200" height="200" style="border: 1px solid"></canvas> <br> <butt ...

Refresh the page and navigate to the last active tab using PHP and jQuery jTable

After a user clicks the submit button on a jquery-jtable form, I am trying to reload the page and navigate to the tab that was active before the reload. However, my current solution only reloads the page without navigating to the previous tab. The tabs are ...

Utilize a single submit button to navigate through multiple pages dynamically using JavaScript

I would like to navigate to different rooms with just one button using JavaScript. For instance, there are three rooms: "Kitchen, Toilet, and Bedroom". How can I utilize JS to enter any of these rooms based on my selection? If I input "kitchen" in the text ...

Master the art of using useMutation from react-query: Learn how to handle error messages and success notifications effectively!

Currently in my Next.js project, I have integrated react-query to retrieve data from MongoDB. Within my form, a POST request is sent using the useMutation hook: /*** components ***/ import {Button, InputGroup} from "../index"; import {useMutatio ...

Using separate files for routes in Express.js can help organize and streamline your code

I'm facing an issue while setting up a node project where I need to organize my files. Specifically, I want to place a file routes.js within the routes/routes.js directory and controllers files in the controllers/ directory. For instance, let's ...

Utilizing absolute path in Typescript: A comprehensive guide

I am currently working on a project written in Typescript running on NodeJS. Within the project, I have been using relative paths to import modules, but as the project grows, this approach is becoming messy. Therefore, I am looking to convert these relativ ...

AngularJS: default radio button selection

I'm currently working on creating a color configurator using AngularJS with radio buttons. Everything seems to be functioning properly - the data binds correctly, etc., but I'm encountering an issue setting the default color radio button as check ...