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

Using JavaScript, you can employ the .split() and .replace() methods on a string value to accurately extract the specific

I'm currently attempting to extract hashtags from a text string by splitting it and removing unwanted HTML tags. Despite my efforts, I haven't been able to achieve the desired outcome. I am seeking guidance on where I might be going wrong. Here ...

Tips for moving text within a Canvas using a button to trigger the function that displays the text in a Javascript environment

Within my HTML, there is a canvas element with the id="myCanvas". When a button is clicked, it triggers this particular function: function writeCanvas(){ var can = document.getElementById("myCanvas"); var ctx = can.getContext("2d"); va ...

The aggregation pipeline in nodeJS with mongoDB is failing to return any results, returning an empty array instead

Currently, I am enrolled in Jonas Schmeddtman's Node.js course where I am working on developing a tour App. However, I have encountered an issue where sending a request via Postman on the specified route results in an empty array instead of the expect ...

Using Django's template tag in conjunction with Vuetify's input value: a comprehensive guide

Is it possible to combine Django's template tag with Vuetify's input value? I found in Vuetify's documentation that the value can be set using the following method: Click here for more information <template> <v-form> < ...

What is the reason for the clearInterval consistently functioning after the completion of the function?

Just starting out in web programming and currently delving into javascript and jquery ajax.. This snippet represents my javascript code. The refresh variable controls an interval for updating the chat by fetching chats from the database and displaying the ...

The TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...

The error message "SharedArrayBuffer is not defined" occurred when attempting to utilize ffmpeg.wasm

<!DOCTYPE html> <html> <head> <title>TikTok Live Downloader</title> </head> <body> <h1>TikTok Live Downloader</h1> <label for="username">Username:</label> ...

AngularJS : "Executing successive promises" with additional functions interspersed

Recently, I encountered a challenge in my Angular project. As a newcomer to Angular, I was tasked with modifying a directive that handles forms to ensure the submit button is disabled during processing and then enabled again once all operations are complet ...

Retrieve the quantity of files in a specific directory by implementing AJAX within a chrome extension

I need assistance with obtaining the count of images in a specific directory using JS and AJAX within my chrome extension. My current code is included below, but it does not seem to be functioning as expected since the alert is not displaying. main.js .. ...

An action in redux-toolkit has detected the presence of a non-serializable value

When I download a file, I store it in the payload of the action in the store as a File type. This file will then undergo verification in the saga. const form = new FormData(); if (privateKey && privateKey instanceof Blob) { const blob = new Blo ...

Trigger an alert after a separate function is completed with jQuery

On my page, I have a function that changes the color of an element. I want to trigger an alert once this action is complete using changecolor(). However, I am unable to modify the changecolor() function due to certain restrictions. Is there a way to dete ...

The Google Docs viewer is displaying an empty screen

I have been utilizing the Google Docs viewer on my website: <div class="embed-r embed-responsive-a"> <iframe class="embed-responsive-it" src="https://docs.google.com/viewer?embedded=true&amp;url=http://LINK.PDF"></iframe> </div& ...

Displaying various Ajax html responses

The function $('.my-button').click(function(e) is designed to display the output of the MySQL query in display.php, presented in HTML format. While it functions correctly, since each button is looped for every post, the script only works for the ...

Can CSS be used to automatically focus on a div element?

Can CSS be used to set autofocus on a div element? <div class="form-group" style="margin-left:10px"> <label for="organizationContainer" class="nmc-label">@Res.GroupStrings.CreateNewGroupOrganization</label> <div id="organiza ...

Sending back an HTTP response code from PHP to AJAX

I'm currently working on creating a login page for a website. The functionality involves using AJAX to send a request to a PHP script that verifies the username and password input. If the query returns a successful result, I use http_response_code(200 ...

Exploring the wonders of LoopBack querying

Discovering loopback has been an enlightening experience for me. However, as I delve deeper into its functionalities, I've stumbled upon something unexpected. I noticed that when executing queries, such as using the updateAll method, if a parameter i ...

Select specific columns from an array using Typescript

I have a collection of objects and I'm looking for a way to empower the user to choose which attributes they want to import into the database. Is there a method to map and generate a separate array containing only the selected properties for insertion ...

The jQuery onClick function functions effectively for the initial two clicks; however, it ceases to

I am currently experimenting with jQuery to dynamically load a specific div from another page on my server into a designated section on the existing page. While the code is successfully functioning for the first two clicks on the website, it fails to work ...

FormData enables uploading of several images through distinct fields simultaneously

Looking to upload images to the server before submitting the form? Unable to nest forms, FormData() is being utilized. The form includes a title and 5 images with captions. The goal is to initiate the upload once an image is selected without clicking &apo ...

Adjusting the StrokeWidth in pixels/em units on fabricjs

When adding a rectangle or circle to the canvas and adjusting the strokeWidth using a range input, how can we determine the value of strokeWidth in pixels, em, or percent? For instance, if we set strokeWidth to 5 within a range of 1-10, how much does the a ...