The Vue select change event is being triggered prematurely without any user interaction

I am facing an issue with my Vue app where the change event seems to trigger even before I make a selection. I tried using @input instead of @change, but encountered the same problem as described below.

I have tested both @change and @input events, but they still fire when the controls load initially.

Interestingly, this was working fine until I made some CSS changes to isolate the component from its surrounding styles. However, I'm puzzled as to why this would affect the behavior.

Any insights on why adding the options tag and contents would cause the change event to fire?

<div class="form-group" :class="{formError: errors.has('formSection')}">
    <label for="formSection">Section*</label>
    {{ formModel }}
    <select
        v-model="formModel.idSection1"
        class="form-control"
        id="formSection"
        name="formSection"
        @input="onChangeSectionLevel1">
        <option v-for="sectionLevel1 in formModel.sectionLevel1" 
                                    v-bind:value="sectionLevel1.value" 
                                    v-bind:key="sectionLevel1.id">
                                    {{ sectionLevel1.value }}
        </option>
    </select>                                
    <span v-if="errors.has('formSection')">This field is required</span>
</div>

Whenever I include the options tag that loops through the items, the onChangeSectionLevel1 function is triggered. I suspected it could be related to vee-validate, but removing it did not resolve the issue.

methods: {
   onChangeSectionLevel1() {
      alert("changed");
      ...
   }
}

Update:

I noticed that when I print out the bound object, it does not contain the idSection1 item.

{
    "idSection2": null,
    "idSection3": null,
}

However, if I add a dummy option like below, all 3 data items including idSection1 are visible, which were missing when looping through with v-for.

<select
    v-model="formModel.idSection1"
    class="form-control"
    id="formSection"
    name="formSection"
    @change="onChangeSectionLevel1">
    <option>Hello World</option>
</select>

The data item now includes idSection1 as well:

{
    "idSection1": null,
    "idSection2": null,
    "idSection3": null
}

Thank you in advance for your help!

Answer №1

Although not a direct answer, the code provided above is functional and operates as intended in js fiddle

Link to JSFiddle Demo

Snippet:

<div id="app">
  <label for="formSection">Section*</label>
  {{ formModel }}
  <select
          v-model="formModel.idSection1"
          class="form-control"
          id="formSection"
          name="formSection"
          @change="onChangeSectionLevel1">
    <option v-for="sectionLevel1 in formModel.sectionLevel1" 
            v-bind:value="sectionLevel1.value" 
            v-bind:key="sectionLevel1.id">
      {{ sectionLevel1.value }}
    </option>
  </select>  
</div>

new Vue({
  el: "#app",
  data: {
    formModel: {
        idSection1: null, 
      sectionLevel1: [
        {
                    id: 1, 
          value: "Section 1"
        }
      ]
    }
  },
  methods: {
    onChangeSectionLevel1() {
     alert("changed");
    }
  }
})

After placing numerous breakpoints, it became evident that the model was being replaced post-page mounting.

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

How can I implement the ternary operator in React Native and resolve my code issue?

Hello, I'm looking to implement the ternary operator in my code. Specifically, I want to render a FlatList if `cookup` has a value. However, if `cookup` is an empty array, I want to display some text instead. <FlatList data={cookUp} ...

Transforming jQuery object into HTML code

I need assistance with a JavaScript task where I am trying to parse and replace an item within an HTML string, but then struggling to convert it back to a string. Specifically, I am having difficulty turning the new jQuery object back to HTML. var compile ...

Managing options post initialization in egjs-flicking: A comprehensive guide

In my Vue2 project, I am currently utilizing egjs-flicking. I am looking for a solution to implement different align options based on the screen size (mobile or desktop). Is there a method to accomplish this without having to destroy or reinitialize the ...

What is the best way to incorporate setTimeout in a loop using Coffeescript?

window.onload = -> boxOrig1 = 10 boxOrig2 = 30 canvasW = 400 canvasH = 300 ctx = $("#canvas")[0].getContext('2d'); draw = (origin,dimension) -> ctx.clearRect(0, 0, canvasW, canvasH) ctx.fillStyle = 'rgb(200,0 ...

Vuetify 2.0: Enhancing Slot Headers

Hello there! I've been working on customizing the slot header for a data table using vuetify.js to incorporate tooltips, which is all going smoothly. However, I'm facing an issue where the arrows for ascending and descending order are not appeari ...

What could be causing the post method to fail in this AngularJS example?

After successfully reading a JSON file in my sample code, I encountered an issue when trying to update the JSON file. The error message "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)" appeared, even though the data ...

When using the UI Router, nested views may display double slashes in the URL and redirect back to

I've been working on editing a project to incorporate a root view/state that encapsulates all other views/states within it. Previously, each page functioned as an independent state, making it cumbersome to implement global changes across all states wi ...

Javascript does not function on sections generated by ajax

I'm facing an issue with a JavaScript function not working on a dynamically generated part using AJAX. Here is the AJAX call: <script> $(window).on('scroll', function() { $("#preloadmore").show(); if ($(window).height() + $(window ...

Utilize localstorage with Redux and Next.js to initialize the state

Having an issue when attempting to populate the initial state from local storage in order to create a store. I encountered the following error message: ReferenceError: localStorage is not defined Here is my store configuration: const store = createStore(r ...

Looking for an uncomplicated SSO system similar to Google Identity Toolkit but with a customizable UI interface?

I'm really impressed with the Google Identity Toolkit, it's so user-friendly and easy to set up! However, I'm having trouble with the fact that it forces me to use its UI. Is there another option available that will allow visitors to simply ...

Delete the item along with its associated data from the local storage upon clicking on an icon

I'm currently working on a To-Do List and facing an issue while trying to delete an item upon clicking a trash bin icon. image The problem I'm encountering is that only one data point is removed from local storage when the icon is clicked. If I ...

Utilizing Jquery functions within the AngularJS framework

Utilizing Uikit along with its pagination feature, I am attempting to implement this function for changing the page: $('[data-uk-pagination]').on('uk-select-page', function(e, pageIndex){ console.log("page " + pageIndex); ...

Changes made to the V-model property will only be reflected after the page is refreshed

I have encountered a situation with two checkboxes that need to reflect the values of watched computed properties. While I can observe reactive changes in my Vue extension when these properties are altered, the updated states of the checkboxes only appear ...

Update search results when performing a new search on a web application (without using jQuery)

My simple web app interacts with an API to retrieve search results from a database and utilizes ajax to insert them into an empty ul element on the page (employing JSONP for cross-domain requests). I am struggling to achieve this functionality using plain ...

Unable to input characters consecutively into the text field because it is being displayed as a distinct function within the component

When attempting to bind a text field using the approach below, I encounter an issue where entering characters in the text field causes the control/focus to shift out of the field after the first character is entered. I then have to click back into the text ...

I am finding the event naming conventions in Vue 3 to be quite perplex

In the parent component, there is a child component: <upsetting-moment-step :this-step-number="1" :current-step-number="currentStepNumber" @showNextStep="showNextStep" ></upsetting-moment-step> The par ...

Combining Node.js and Express to display error and success modals simultaneously in case of errors

I'm currently working on web development using Node.js and Express, while also exploring Reactive Programming with the libraries recommended by my seniors. My specific task at the moment involves creating a Change Password form for users. This form sh ...

Is there a method in CSS animations that allows for endlessly repeating successive animations in a specified sequence?

While working with CSS animations, I encountered a challenge of making two animations occur successively and repeat infinitely without merging keyframes. Is there a way to achieve this using only CSS? If not, how can I accomplish it using JavaScript? I a ...

What could be causing the issue with lodash throttle not functioning correctly in the useWindowSize custom hook?

I'm attempting to implement a resize event with throttle, but I'm encountering an issue. To troubleshoot, I have tried the following: import {throttle} from 'lodash' export function useWindowSize() { const [windowSize, setWindowSize] ...

Exploring the relationship between React component inheritance and asynchronous requests

I'm struggling to comprehend why this isn't functioning var link = window.location.href; var array = link.split('/'); var sub = array[array.length-1]; console.log(sub); var name; var posts; var upvotes; var ProfileFiller = React.creat ...