How to automatically choose the first option in a v-for loop in Vue.js

I have a loop that creates a dropdown menu from an array:

 <select class="form-control" v-model="compare_version" >
            <option
              v-for="(version, index) in allVersions"
              v-bind:value="index"
              v-bind:key="version.versionid"
              :selected="version.versionid === 0"
            >{{ version.versionid }}</option>
          </select>

My goal is to set the first value of the dropdown as the default.

The options are showing up but the first one is not being selected by default.

Can anyone spot the mistake in my code? Your help would be much appreciated!

Answer №1

To set the default value as 0 for compare_version, you can do so within the data() function while binding the index from the iterating list as the captured value in the model. The use of v-model will handle this process efficiently.

Furthermore, it is advisable to remove the :selected binding when keeping in mind that the captured value from the select tag corresponds to the index of the list.

var vm = new Vue({
  el: "#vue-instance",
  data: {
    compare_version: 0,
    allVersions: [
      {versionId: 'A'},
      {versionId: 'B'},
      {versionId: 'C'}
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
 <!DOCTYPE html>
<html>
<body>
<div id="vue-instance">
<select v-model="compare_version">
    <option v-for="(x,index) in allVersions"
            v-bind:value="index"
            v-bind:key="x.text">{{x.versionId}}</option>
  </select>
  <span>Selected: {{ compare_version }}</span>
</div>
</body>
</html> 

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

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Tips for capturing the current terminal content upon keypress detection?

After successfully installing the terminal on a test page, I am looking to highlight matching parentheses within it. This is similar to what is done in this example: I have a working solution in place and now need to integrate it with the terminal. ...

The animation speed of the jQuery hashchange event is set to zero, causing the animation

I'm facing an issue with jQuery where my animation inside a hashchange event is not smooth; it happens instantly when triggered. I'm looking for a way to make the animation smoother. jQuery( document ).ready(function() { jQuery(window).on(&a ...

An odd issue has arisen where the website functions properly in Firefox 3.0 but encounters problems when accessed in Firefox 3

Could someone investigate this issue for me? When you click on the showcase and then on the logo, a modal window should open with the logo. It works perfectly in FF 3.0, but in FF 3.5, the tab switches from showcase to home after clicking the logo. Even ...

What is the best way to delete a property from an object in an array using Mongoose? This is crucial!

Doc - const array = [ { user: new ObjectId("627913922ae9a8cb7a368326"), name: 'Name1', balance: 0, _id: new ObjectId("627913a92ae9a8cb7a36832e") }, { user: new ObjectId("6278b20657cadb3b9a62a50e"), name: 'Name ...

Issue with jQuery's outerHeight() function persisting despite attempting to fix it with jQuery(window).load()

Once the content is loaded using AJAX, I need to retrieve the outerHeight of the loaded elements. Ajaxload file: $('#workshop').submit(function(event){ $.ajax({ url: URL, type: 'POST', data: $(' ...

I've noticed that every time I use the simple-encryptor npm to encrypt something, the output is always different

Can you assist me in solving this issue? var key = 'real secret keys should be long and random'; // Generating an encryptor: var encryptor = require('simple-encryptor')(key); var encryptedText = encryptor.encrypt('testing') ...

In my Angular application, I have two div elements that I want to toggle between. When a button located in the first div is clicked, I need

I am working on a code snippet that requires me to hide div1 and display div2 when the button in div1 is clicked using Angular HTML5. Currently, I have two separate modal pop up template files and JS controllers for each of them. Instead of having two po ...

Centered iframe within a div

I am trying to center my iframe within a white box and need some assistance with this. I want the iframe to be in the middle of the white box rather than its current position at the moment. game1.html: <html> <head> <title>R ...

I'm trying to determine which jQuery event would be more beneficial for my needs - should I go with

I'm facing a dilemma On my website, I need to capture the value of a span within a modal. The value changes when the modal is opened and reverts to the old value when closed. This particular value represents the cart total in my online store. Wheneve ...

Creating multiple objects using a single object in JavaScript can be achieved by using the concept of object

When presented with the following data structure: { "time_1": 20, "time_2": 10, "time_3": 40, "time_4": 30 } and expecting a result in this format: [ { "key1": "time_1" ...

Placing JavaScript at the bottom of the page, sourced from a Partial Page

I'm trying to display JavaScript code from a Razor Partial Page at the bottom of a (layout) Page. In a similar discussion on Stack Overflow about Including JavaScript at bottom of page, from Partial Views, it was suggested by user Becuzz that using a ...

Checking the types of arrays does not function properly within nested objects

let example: number[] = [1, 2, 3, 'a'] // this code block correctly fails due to an incorrect value type let example2 = { demo: 1, items: <number[]> ['a', 'b'], // this code block also correctly fails because of ...

Issue: Encounter of "Uncaught (in promise) TypeError" while implementing RiveScript chatbot in Angular

I've been working on integrating a chatbot based on RiveScript into Angular. The chatbot is functioning well - I always see the correct response in the console. Displaying the user's input is also working seamlessly. However, I'm encounterin ...

How can I choose records from collection 'x' in mongodb?

I need to fetch all fields from my database using an API call Here is my code: exports.objfields = async (req, res, next) => { try { var db = mongo.connection; var objeto = req.headers.objeto; const result = db.db.collection(objeto).find( ...

What is the best way to combine Bootstrap and custom CSS, specifically the home.module.css file, in a React project?

I'm currently experimenting with utilizing multiple classes to achieve an elevated button effect and a fade animation on a bootstrap card. Here's the code snippet I've been working on: import Head from 'next/head' impo ...

Issue with JQuery: object.id is returning as undefined even though it should have a value

While working with JQuery, I encountered a rather peculiar (or possibly foolish) error. The HTML code snippet in question is as follows: <input type="password" name="repeatPassword" id="id_repeatPassword" /> And within my javascript code, I have t ...

Surprising outcome arising from simultaneous execution of numerous asynchronous operations on every individual object within an array

I'm fairly new to working with Node.js and I'm still trying to grasp the concept of callbacks and the asynchronous nature of Node.js. However, I've encountered a problem that I can't seem to solve. I've already searched extensively ...

Generating a USA map with DataMaps in d3jsonData

I'm trying to create a basic US map using the DataMaps package and d3 library. Here's what I have attempted so far: <!DOCTYPE html> <html> <head> <title> TEST </title> <script src="https://d3js.org/d3.v5.js"> ...

A step-by-step guide on uploading a CSV file in Angular 13 and troubleshooting the error with the application name "my

I am currently learning angular. I've generated a csv file for uploading using the code above, but when I try to display it, the screen remains blank with no content shown. The page is empty and nothing is displaying Could it be that it's not ...