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

Problem with AngularJS Multiselect checkbox dropdown configuration

In my application, I have a pop-up that includes a multi-select dropdown menu. Here is the code for the Multi-Select Dropdown: <select name="edit_tags" class="form-control" id="advisor_article_tagsx" multiple="" required ng-model="article_selected ...

Error: The function you are trying to reference is undefined

I am facing an issue where I am receiving a "ReferenceError: doNotification is not defined" message when attempting to display a pop-up notification upon successful promise. Oddly enough, triggering doNotification on button click within my HTML works wit ...

An easy way to create an input field after clicking a button

When I try to add a field on Button Click, the default field is not showing and does not get added upon button click I have put in my best effort but I cannot figure out what the problem is. I have added functions and used Math to generate a unique id. Th ...

The intricate dance between JAVA and HTML

Can Java be compatible with HTML and JS? Is it possible for them to cooperate without using JSP? In order to connect the WEKA function, we utilized Java code through a JAR file, but now we also require HTML and JS links for visualization. Is there an alte ...

Exposing a Hidden Division with a Link via jQuery

I currently have a jQuery Panel set up to open when clicking a button. Now, I am looking to add a second link at the bottom of the page that will also open the same panel. Can anyone provide guidance on how to accomplish this? You can view my JSFiddle a ...

I am unable to get the radio button checked in Angular 2

I have set up a form with two radio buttons for gender selection, and I want to ensure that the previously selected option is displayed as checked. Here's the code snippet I've added in my template: <div class="form-group"> <label& ...

Conversion of UTC timestamp to a timestamp in the specified timezone

this.selectedTimezone="Pacific/Kiritimati"; //this value will come from a dropdown menu These records represent the data.body returned by an API call. Iterating through each record in the dataset: { We are creating a new Date object based on the ...

Is the Spring MVC ModelAndView object being returned?

After clicking a link on a jsp page, I have a GET method that is instantiated as: HTML: <div class="panel accordion clearfix" id="dispdir"> <script type="text/javascript"> window.onload = function() { //showDirectorySe ...

Guide to sending and receiving JSON data using XAMPP PHP

Currently, my XAMPP 7.1.10-0 server is up and running with the following index.php file: <?php if(isset($_POST["username"])) { echo $_POST; header("Location:getbooks.php"); exit; } else { echo file_get_conten ...

Infinite scrolling made effortless with jQuery and Ajax

I am attempting to create a basic infinite scroll feature that monitors when the user scrolls to the bottom in an HTML file. Once the bottom is reached, it should then load additional content from another HTML file which contains more text. The second HTM ...

Every time I alter the pathway, the music suddenly ceases. How can I create a constantly changing audio experience?

I'm facing an issue with a dynamic audio player on my website. On a page featuring music, when I click 'play' on any song, it triggers a function: playSong (song) { var payload = { name: song, audio: new Audio(require(` ...

Discover a foolproof method for effortlessly examining an flv or mp4 file embedded within a webpage simply by

I've encountered a challenge with JavaScript. I can successfully check a flash object in a webpage when hovering over it, but I'm unsure how to achieve the same for flv or mp4 objects when either hovering over or moving away from them. Currently ...

Encountered an Uncaught ChunkLoadError with Vercel Next.js: Chunk 0 failed to load

Upon removing the node modules and package-lock.json files, I encountered the error mentioned above when attempting to reload any page. The project works fine after being restarted for the first time. However, upon reloading the page again, it displays a b ...

Guide on dynamically importing a module in Next.js from the current file

I am facing a challenge where I have multiple modules of styled components in a file that I need to import dynamically into another file. I recently discovered the method for importing a module, which requires the following code: const Heading = dynamic( ...

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

Is there a way to automatically refresh a page as soon as it is accessed?

My goal is to create a page refresh effect (similar to pressing Command+R on Mac OS) when navigating to a certain page. For instance: Currently, when I navigate from "abc.com/login" to "abc.com/dashboard" after successfully logging in, the transition occ ...

What is the best way to modify the text color within a Navbar, especially when the Navbar is displayed within a separate component?

First question on StackOverflow. I have a Next App and the Navbar is being imported in the _app.js file. import Navbar from "../Components/Navbar"; function MyApp({ Component, pageProps }) { return ( <> <Navbar /> ...

Unable to retrieve HTML content through a Node.js server

I created a HTML webpage that includes .css, images and JavaScript files. However, when I start my node server using the command below: app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); The webp ...

There is no information available at this time

Currently, I am delving into Angular and am keen on creating a web application that consumes a Restful Web service. The setup of my page is as follows: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html ng-app="Tri ...