Choose 2 markup elements to shift to the row above

I am encountering a bug in my vuejs application where deleting one element causes the previous select2 value to be applied to the wrong row. This issue occurs when looping through an array and outputting multiple select2 elements with delete buttons next to them.

For a demo, you can visit: https://jsfiddle.net/3oqsmw0z/1/

The deletion of items is done by index using the following code:

deleteItem: function(index) {
    console.log('deleteItem');
    this.mySelects.splice(index, 1);
}

To replicate the issue:

Select the first option in the first select, the second option in the second select, then the third option in the third select. Now, delete the second option. Instead of showing options one and three as expected, it displays the selected option from the deleted second element. The label indicates it's the third element, but the selected option belongs to the second element.

Answer №1

After deleting the second element, the value for the third element is reset and triggers the value watcher handler. In the handler, an attempt is made to update the value using jQuery:

watch: {
    value: function (value) {
      // update value
      $(this.$el).val(value)
    },...

However, this approach does not work as it fails to trigger the change event, causing Vue not to render any changes.

To resolve this issue, explicitly fire the change event:

 watch: {
    value: function (value) {
      // update value
      $(this.$el).val(value).trigger('change')
    },...

In addition, there seems to be an initialization problem with your select elements in the demo you provided. The values passed should determine the initial selection for each select:

mySelects: [
      {label: 'first', val: 1},
      {label: 'second', val: 2},
      {label: 'third', val: 3}
    ],...

To address this, follow these steps:

  1. Explicitly trigger the change event after setting the value
  2. Set the value after passing the options
 mounted: function () {
    var vm = this
    $(this.$el)
    // first pass the options
      .select2({ data: this.options })
    // then set the value
      .val(this.value)
    // explicitly trigger change event to prompt DOM update by Vue
      .trigger('change')
    // emit event on change.
      .on('change', function () {
        vm.$emit('input', this.value)
      })
  },

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 you achieve three layers of nested quotes in Dynamic HTML?

Working on an app that utilizes JQuery and JQTouch for iOS. The issue I'm facing involves dynamically generated HTML lists where the user clicks a row that needs to be highlighted. However, achieving this has proven tricky due to nesting 3 sets of quo ...

preventing further executions by halting a function after the initial click

I've come across this function: function display() { $.ajax({ url: "new.php", type: "POST", data: { textval: $("#hil").val(), }, success: function(data) { ...

Can Next.js 13 support the usage of axios?

Despite trying to implement the SSG operation with the fetch option {cache: 'force-cache'}, I consistently received the same data even when the mock server's data changed. I found that using the fetch option {cache: 'no-store'} do ...

Checkbox change cannot be initiated

Using jQuery version 1.8.3, I am attempting to trigger a state change for each checkbox. The following code works when placed inside a click event: $("#btn_off").click(function(){ $( "tr td input" ).each(function( index ) { if ($(this).is(":ch ...

Modifying the language setting in React Native for user interface preferences

After successfully setting up react-native-i18n and verifying its functionality, I encountered an issue. I am looking to dynamically change the locale within the React Native app itself. To attempt this, I included a button using Touchable Opacity and imp ...

Deciphering JavaScript Arrays

Looking to extract the values of {r=1, g=4, b=6} from an array. Any suggestions on how to store each individual value (r, g, b) in its own variable? ...

Assistance needed for iterating through JSON data

I need assistance retrieving specific data from a JSON response in my JavaScript code. Unfortunately, the current approach is not providing the desired results: This is my JavaScript code snippet: function retrieveArtists(response){ var artistList ...

Function exhibiting varying behavior based on the form from which it is called

Currently, I'm utilizing AJAX to execute a server call, and I've noticed that the behavior of my function varies depending on its origin. Below is an excerpt of the code that's causing confusion: <html> <body> <script> ...

Tips on Using Firebase Database Rules to Validate a Node Property Value Against the User's Unique ID

I am currently utilizing the Firebase database and I am in the process of configuring rules to restrict write access to users whose uid matches the userId node of the object they are attempting to write, while still allowing the creation of new objects suc ...

assisting with the transition effect using CSS3, JS, or jQuery

I am looking to alter the background-image of this particular image when transitioning to another one from my images folder, similar to this example. Below is the code that I have: CSS .image { position: relative; overflow: hidden; -webkit-tr ...

How do I resolve the issue of PHP sendmail form sending empty emails and fix the JavaScript?

I spent the whole day dealing with sendmail.php. Initially, I had an issue with not receiving emails, which I managed to fix. However, after that, I started receiving blank emails. It wasn't a problem with my PHP or HTML code, but rather with the Java ...

Understanding the application of JSON data can be simplified by following these

I am looking to manipulate dates by either adding or subtracting them, but I am unsure of how to extract the dates from the other data present. var fetch = require('node-fetch'); fetch('https://api.nasa.gov/planetary/earth/assets?lon=100.7 ...

Is it common for the vuetify main.sass bundle file to have a gzipped size of 30 kilobytes?

Just a quick question: Is the file size considered normal? Will it still contain all component stylings even if removed by treeshaking? Treeshaking is enabled. Any advice would be greatly appreciated! https://i.stack.imgur.com/VKaQQ.png ...

Transforming HTML with JavaScript

I am facing a challenge in my JavaScript application where I receive HTML code from an endpoint that contains radio buttons. Unfortunately, I cannot modify the HTML content coming from this endpoint. My goal is to convert these radio buttons into regular b ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

Is there a way to determine the color of an element when it is in a hover state?

I recently started using the Chosen plugin and noticed that the color for the :hover on the <li> elements is a bright blue. I want to change it to a bold red color instead. https://i.stack.imgur.com/mcdHY.png After inspecting it with the Chrome too ...

Angular feature for adding a "new row"

I am in the process of creating a tool for a website that serves as a "deal builder". Within this builder tool, there is a button labeled "add new item" which will insert a new device item into the <li> list. <ul class="deal-builder-devices enti ...

Angularjs - Provider not recognized:

I'm encountering an issue that keeps popping up: Error: [$injector:unpr] Unknown provider: UsersServiceProvider <- UsersService I attempted to address this problem by adding ['UsersService' before my controller function, after reading a ...

Using Javascript, incorporate a string variable into the response

Currently, I'm working with a node.js program and I've come across this response: 'Content-Disposition': 'attachment; filename="tts.mp3"' Instead of using "tts.mp3," I have a variable named textToConvert. How can I modify it ...