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

"Assigning an array as a value to an object key when detecting duplicates in a

Let's assume the table I'm iterating through looks like this: https://i.stack.imgur.com/HAPrJ.png I want to convert each unique value in the second column into an object, where one of the keys will hold all values from corresponding rows. Here& ...

Unexpected results from the match() function

Attempting to utilize the RegExp feature in Javascript (specifically with the match function) to locate instances of a sentence and a specific word within that sentence embedded in the HTML body. Provided is some pseudo-code for reference: <!DOCTYPE ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

The automated Login Pop Up button appears on its own and does not immediately redirect to the login form

Hey guys, I'm struggling with modifying the jquery and html to ensure that when the login button is clicked, the login form pops up instead of displaying another login button. Another issue I am facing is that the login button seems to pop up automati ...

The entire DOM refreshes when a user updates the input field

In my React component, I am managing two states: inputText and students. The inputText state tracks the value of an input field, while the students state is an array used to populate a list of student names. The issue arises when the inputText state change ...

Getting rid of a cookie from the header in Reactjs

Currently, I'm developing an application with Reactjs and utilizing the Next.js framework. To manage user authentication, I've implemented cookies. However, I am facing a challenge when it comes to logging out users and removing the cookie. Could ...

What is the process of encapsulating a callback function within another callback function and invoking it from there?

Here is the code snippet I am working with: var me = this; gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) { if (authResult && !authResult.error) { me ...

The jquery fancybox ajax modal popup fails to display in Internet Explorer 7

Recently, I utilized JQuery fancy box for the first time to display a menu list. When clicking on a specific item, the page is rendered properly in an iframe. However, if there is already an AJAX model popup present on the rendered page, it doesn't di ...

The process of mounting a Vue component involves removing the surrounding div element

I am facing an issue while mounting a component on a function. Everything seems to be working fine initially. However, I have configured it to destroy the div after a certain number of seconds. The problem arises when I attempt to add the component again; ...

Ways to have MongoDB present nested JSON data as an array?

I recently came across some interesting data: { "_id" : ObjectId("5461e16ee7caf96f8f3584a2"), "num_marcacao" : "100", "sexo" : "Fêmea", "idade" : "20", "bigdata" : { "abortos" : [ { "data_aborto" : ...

"Validation with Express-validator now includes checking the field in cookies instead of the request

My current validator is set up like this: const validationSchema = checkSchema({ 'applicant.name': { exists: true, errorMessage: 'Name field is required', }, }); and at the beginning of this route (the rest is not relevant) ...

Looking for assistance on how to access a JSON file in JavaScript without the need for servers

As I embark on my journey with JavaScript, a question has been lingering in my mind - is it possible to access a JSON file locally, without the need for servers like WAMP? My goal is to simply retrieve the data from a JSON file and display its contents o ...

Function returning undefined when accessing prototype property in JavaScript

When attempting to create an image rotator using prototypal inheritance, I am encountering an error in the console showing: TypeError: this.curPhoto is undefined this.curPhoto.removeClass('previous'); I have placed this code in the callb ...

How can you use JavaScript to create a JSON object using values from an HTML form textarea and then send

I need to create an HTML form that will send specific information in the Http-request body. { “info” : { “id” : “123” “text1” : <data from html text-box> } Therefore, my goal is to convert the provided data into a JavaScri ...

Tips for aligning a row at the bottom within a nested column

Desired Outcome I am struggling to arrange two smaller images next to a larger image using Bootstrap 4. Specifically, I am having difficulty aligning one of the smaller images at the bottom so that it matches the alignment of the larger image. The layout ...

What is the process of converting TypeScript to JavaScript in Angular 2?

Currently diving into the world of Angular 2 with TypeScript, finding it incredibly intriguing yet also a bit perplexing. The challenge lies in grasping how the code we write in TypeScript translates to ECMAScript when executed. I've come across ment ...

Displaying a page using express.Router()

I'm having trouble figuring out how to incorporate EJS rendering into a file utilizing express.Router(). The usual method of router.set('view engine', 'ejs') doesn't seem applicable in this context. Any ideas on how I can succ ...

Applying class to target specific screen size in Bootstrap

I've been utilizing bootstrap for my project. My objective is to assign multiple classes based on screen size, such as sm-col and xs.col. For example, let's say I have a text id <div id="text" class="xs-format lg-format ..."></div> ...

Utilize CSS to break apart text (text = white space = text) and align text in a floating manner, allowing

Is there a way to use CSS to create a white space in the middle of text? Currently, I am manually breaking the text, which is not ideal. I am aware that there is a function that allows the text to end and start in another div, but unfortunately, it is not ...

Using Rails to render a partial containing a form object

I need help with rendering a partial called 'colordata' after selecting a color from a dropdown list using Ajax. Unfortunately, I'm not seeing any changes on the main page and the form is undefined in the colordata partial. This is the sche ...