Is there a way to make a selected option stay selected in vue.js 2?

Here is the structure of my Vue component :

<template>
    <select class="form-control" v-model="selected" :required @change="changeLocation">
        <option :selected>Choose Province</option>
        <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
    </select>
</template>

I have used

<option :selected>Choose Province</option>
for selection purposes

However, when I run it with gulp watch, an error occurs

The error message reads as follows :

ERROR in ./~/vue-loader/lib/template-compiler.js?id=data-v-53777228!./~/vue-load er/lib/selector.js?type=template&index=0!./resources/assets/js/components/bootst rap/LocationBsSelect.vue Module build failed: SyntaxError: Unexpected token (28:4)

It appears that I might have made a mistake somewhere

How can I resolve this issue?

Answer №1

Resolving Error Issues

You may have mistakenly connected properties to nothingness. This is evident with the use of :required in

<select class="form-control" v-model="selected" :required @change="changeLocation">

and :selected in

<option :selected>Choose Province</option>

To rectify this issue, revise your code as follows:

<template>
  <select class="form-control" v-model="selected" :required @change="changeLocation">
    <option>Choose Province</option>
    <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
 </select>
</template>

Setting Default Values for Select Tags

  1. In order for v-model to function correctly, you must create a data property named selected. Do so by implementing:

    {
      data () {
        return {
          selected: "Choose Province"
        }
      }
    }
    
  2. If the above method seems complex, an alternate approach involves:

    <template>
      <select class="form-control" :required="true" @change="changeLocation">
       <option :selected="true">Choose Province</option>
       <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
      </select>
    </template>
    

Determining the Suitable Methodology

  1. Utilize the v-model method if your default value is dependent on a data property.

  2. Select the second method if your initial selection should be the first option.

  3. For programmatic control, opt for the following technique:

    <select class="form-control" :required="true">
      <option 
       v-for="option in options" 
       v-bind:value="option.id"
       :selected="option == '<the default value you want>'"
      >{{ option }}</option>
    </select>
    

Answer №2

To simplify things, you can choose to either set the selected option as true or false.

<option :selected="selectedDay === 1" value="1">1</option>

In this scenario, the data object looks like:

data() {
    return {
        selectedDay: '1',
        // [1, 2, 3, ..., 31]
        days: Array.from({ length: 31 }, (v, i) => i).slice(1)
    }
}

This snippet demonstrates setting the selected month day:

<select v-model="selectedDay" style="width:10%;">
    <option v-for="day in days" :selected="selectedDay === day">{{ day }}</option>
</select>

Within your dataset:

{
    data() {
        selectedDay: 1,
        // [1, 2, 3, ..., 31]
        days: Array.from({ length: 31 }, (v, i) => i).slice(1)
    },
    mounted () {
        let selectedDay = new Date();
        this.selectedDay = selectedDay.getDate(); // Updates selectedDay to today's date
    }
}

Answer №3

<select v-model="challan.warehouse_id">
<option value="">Select Warehouse</option>
<option v-for="warehouse in warehouses" v-bind:value="warehouse.id"  >
   {{ warehouse.name }}
</option>

You can assign the value of "challan.warehouse_id" from the data retrieved from the API call to edit a challan:

editChallan: function() {
    let that = this;
    axios.post('/api/challan_list/get_challan_data', {
    challan_id: that.challan_id
 })
 .then(function (response) {
    that.challan = response.data;
 })
 .catch(function (error) {
    that.errors = error;
  }); 
 }

Answer №4

To fix the issue, you just have to eliminate v-bind (:) from selected and required attributes. Here's how you should modify it:

<template>
    <select class="form-control" v-model="selected" required @change="changeLocation">
        <option selected>Choose Province</option>
        <option v-for="option in options" :value="option.id" >{{ option.name }}</option>
    </select>
</template>

The reason for the error is that these attributes are not actually binding anything to the Vue instance.

Answer №5

Here is my code snippet for implementing reactive multiselect functionality:

data() {
    return {
        article: {title: 'aaaaa', 'categoriesIds': [1,3], ...},
        selectCategories: {1: 'xxx', 2: 'www', 3: 'yyy', 4: 'zzz'},
    }
},

This is the template section where the multiselect feature is defined:

<div class="form-group">
     <label for="content">Categories</label>
     <select name="categories" 
         v-model="article.categoriesIds" 
         id="categories" 
         multiple 
         class="form-control col-md-5" 
         size="6">
         <option v-for="(category, key) in selectCategories" 
             :key="key" 
             v-bind:value="key">{{category}}</option>
     </select>
</div>

The selected items from the multiselect are linked to the article.categoriesIds array.

Answer №6

One effective method that I frequently rely on is to incorporate a directive into your VueJS initialization in app.js or wherever you are setting up VueJS, for example:

Vue.directive('attr', (el, binding) => {
  if (binding.value === true) binding.value = ''
  if (binding.value === '' || binding.value) {
    el.setAttribute(binding.arg, binding.value)
  }
})

You can then use v-attr to define an attribute, for instance:

<option value="Western Australia" v-attr:selected="form.state == 'Western Australia'">Western Australia</option>

Answer №7

My understanding is that the primary objective here is to designate "Choose Province" as the default option. After experimenting with different approaches, I found that sticking to a simple solution yielded the best results for me:

<template>
    <select class="form-control" v-model="selected" :required @change="changeLocation">
        <option>Choose Province</option> # just an option with no pre-selected or assigned value
        <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
    </select>
</template>  

Answer №8

To implement this, utilize the v-model attribute within the select tag and incorporate the useForm library from Vue. Set the default value of form.category to 'choose' or any other preferred default value.

<script setup>
import { Head, Link, useForm } from '@inertiajs/vue3';
const form = useForm({
    category: 'choose',
    file: null,
});
</script>

<template>

                    <div class="grid grid-cols-1 gap-5">
                        <label for="category" class="font-black">Choose A Category</label>
                        <select id="category" v-model="form.category" required >
                            <option value="choose" disabled>choose</option>
                            <option value="Other">other</option>
                        </select>
                        <div class="bg-red-200 rounded-lg p-2" v-if="form.errors.category">
                            {{ form.errors.category }}
                        </div>
                    </div>


</template>

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

Unable to execute click events on JavaScript functions after updating innerHTML using PHP and Ajax

To begin, I want to clarify that I am intentionally avoiding the use of jQuery. While it may simplify things, it goes against the purpose of my project. Please note that 'ajaxFunction' serves as a generic example for AJAX requests using GET/POST ...

Using the 'onended' audio event emitter in Angular 2 along with a local member of the Component

I'm looking for assistance on how to utilize audio.onended() in order to play the next song in a playlist. I can successfully add songs to the playlist and play them using the above method with an audioObject. However, when audio.onended triggers, I ...

How can AngularJS utilize ng-repeat and ng-bind-html to display arrays of HTML strings?

I'm currently attempting to display HTML strings from an array of HTML strings in my AngularJS project. As a newcomer to AngularJS, I have been trying to follow the examples provided on the official AngularJS website, but I am struggling to find a sui ...

Place an image at the top of the canvas at a specific location

Currently, I am in the process of reconstructing this specific website My approach involves working with React (similar to the aforementioned site) and utilizing the same cropper tool that they have implemented. For cropping, I am incorporating react-imag ...

How can I maintain the selected state of checkbox and radio button in ReactJS after page refresh?

I am facing an issue with my multistep form that contains radio buttons and checkboxes from material UI. Although the data is stored correctly in state and local storage, when I move to the next page and then return, the selections appear unselected to the ...

Creating a row of aligned card components in React

Recently, I began learning React and successfully created a card component using Material UI. However, this time around, I'm attempting to create it using axios and map() methods. I expected the cards to be displayed in the same row horizontally, not ...

Sorry, I'm unable to determine the value of 'title' because it is undefined

Here is the code for the "singleCard" component. When passing {{card.title}} and {{card.body}}, an error occurs: **Error in render: "TypeError: Cannot read property 'title' of undefined" found in ---> <SingleCard> at src/components/sing ...

Responsive design in Android does not function as intended

My goal is to create a responsive design for my website, but I am encountering issues with importing the CSS files into the HTML. When I try to view the site in both the Windows version of Chrome and the Android version, all I see is a white screen. I am c ...

What is the best way to assign a value to a property in a Controller or Global Variable using jQuery?

On my ASP MVC 5 site, I have a checkbox within the NavBar element. This checkbox's state dictates whether or not the Grid will display Inactive records alongside active ones on each page. In an attempt to have all controllers access the same property ...

Utilize jQuery post to send a request to a particular function located at a given URL

Is there a way to accomplish the following: $.post( "functions.php", { name: "John", time: "2pm" }) .done(function( data ) { alert( "Data Loaded: " + data ); }); Instead, is it possible to direct your data to a particular function in "functions.p ...

Jquery Query: Is it possible to incorporate variables into CSS properties?

I manage a website that supports multiple languages, and I want to adjust the position of my container based on the selected language. To achieve this, I attempted the following code: prop = lang == 'ar' ? 'right' : 'left'; $ ...

When attempting to launch a VUE project on Nginx, there seems to be an issue locating static files such as css and

Currently running on a Windows operating system, I am trying to deploy a VUE project on an Nginx server. To build the VUE project: Follow these steps: Navigate to E:\test\test-project-frontend-demo Run npm install && npm run build Up ...

Unable to locate the <router-view> component within VueRouter

I recently completed a project using Vue.js 3.2.13 and Vue-Router 4.0.14. Despite my efforts to ensure everything was set up correctly, I encountered an error in the browser that said "[Vue warn]: Failed to resolve component: router-view". The specific lin ...

Adjust a sub-document field using mongoose

My foundational structure var GameChampSchema = new Schema({ name: String, gameId: { type: String, unique: true }, status: Number, countPlayers: {type: Number, default: 0}, companies: [ { name: String, login: String, pass: ...

Failed Cross-Origin Request Sharing in AngularJS 1.4

I'm currently working with AngularJS version 1.4.3 and here is the code snippet I am using: angular .module('app', []) .run(run); function run($http) { a = $http({ method: "GET", url: 'http://127.0.0 ...

Fetching URL from Right Before Logging Out in Angular 2 Application

I am struggling to capture the last active URL before logging a user out of my Angular 2 app. My goal is to redirect them back to the same component or page once they log back in. Currently, I am using this.router.routerState.snapshot['url'] to r ...

Creating dynamic child components in Vue.js version 2

I am currently developing a facet search system using VueJS. The concept is fairly straightforward: Within a FilterGroup component lies the overarching filter logic. This component allows for several child components, such as AttributeXYZFilter, to provid ...

Retrieve a variety of items and pass them to a view using the mssql module in Node

I'm facing an issue while trying to retrieve data from multiple tables and pass them to my view. Below is the snippet of code I've written that's causing the error. router.get('/', function(req, res, next) { sql.connect(config ...

Upon loading, the IntersectionObserver immediately declares the isIntersecting property true for all elements

Yesterday, when I executed this code, everything functioned as expected. The observer successfully loaded the images once they intersected the viewport: <template> <div id="gallery" class="gallery"> <div class=" ...

What is the reason for the neglect of this function's definition?

Is there a reason behind the error message I am receiving? TypeError: getStatusCode(...) is not a function This error occurs when I execute the following code: const getStatusCode = require('./getStatusCode') tmpStatus = await getStatusCode({url ...