Removing dynamic input fields with VueJS

Need some help with deleting fields in Vue. Managed to get them to render, but not sure how to remove them. I added an index option in the v-for directives, but now I'm stuck. Any suggestions would be appreciated!

If you want to see my code in action, check out this JSFiddle: https://jsfiddle.net/xu55npkn/

<body>

<div id="app"></div>

<script>

const createNewOption = () => { 
    return {
    text: '',
    isAnswer: false
  }
}

const createNewQuestion = () => {
  return {
    text: '',
    options: [createNewOption()]
  }
}

  var vm = new Vue({
    el: '#app',
    template: `<div class="quiz-builder container">
<div v-for="question in questions">
  <div class="input-group">
    <input type="text" class="form-control" v-model="question.text" placeholder="Enter a question">
    <span class="input-group-btn">
      <button class="btn btn-danger" type="button">X</button>
    </span>
    <span class="input-group-btn">
      <button class="btn btn-secondary" type="button" @click="addOption(question)">Add an option</button>
    </span>
  </div>
  </br>
  <div class="input-group" v-for="(option, index) in question.options" style="margin-bottom: 20px">
    <span class="input-group-addon">
      <input type="checkbox" v-model="option.isAnswer">
    </span>
    <input type="text" class="form-control" v-model="option.text" placeholder="Enter an option">
    <span class="input-group-btn">
      <button class="btn btn-danger" type="button">X</button>
    </span>
  </div></br>
</div>
<button class="btn btn-default" @click="addQuestion" :disabled="questions.length >= 5 ? true : false">
  Add another question
</button>
<button class="btn btn-primary" style="background-color: #ffcc00; border: #ffcc00">
  Create quiz
</button>
</div>`,
    data () {
    return {
      questions: [createNewQuestion()],
      showQuestions: false,
    }
  },
  methods: {
    addQuestion () {
        this.questions.push(createNewQuestion())
    },
    removeQuestion (index) {
       this.questions.shift(index)
    },
    addOption (question) {
        question.options.push(createNewOption())
    }
  }
})

</script>

Answer №1

After reviewing your updated query, it appears you have managed to figure out how to remove questions. However, yev's solution provides a more efficient method for handling question removal.

If you want to delete options instead, you will need to create a new function called removeOption. This function should take both the question and option as parameters since you will be iterating over both. Vue simplifies this process for you. Simply locate the index of the option within the array and use the splice method to remove it. For a live example, refer to this demo.

Here is how you can set up the template:

<button class="btn btn-danger" type="button" @click="removeOption(question, option)">
    X
</button>

And here is the component code:

removeOption (question, option) {
    var index = question.options.indexOf(option);
    if (index > -1) {
        question.options.splice(index, 1);
    }
}

Answer №2

Here is the suggested code for your delete button:

<div v-for="(item, index) in items">
  <div>
    <input v-model="item.text">
    <span>
      <button @click=removeItem(index)>Delete</button>
    </span>
    <span>
      <button @click="addItem(item)">Add new item</button>
    </span>
  </div>
</div>

Make sure to include the index parameter in the loop and click handler for the "Delete" button.

Your remove function should be defined as follows:

removeItem (index) {
  this.items.splice(index, 1);
}

Using Array.shift would only remove the first item in the array, which may not be what you intend.

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

Issues with the History API in AJAX Requests

Recently, I have come across a dynamically generated PHP code: <script> parent.document.title = 'Members | UrbanRanks'; $("#cwrocket_button").click(function(){ $("#module").load("modu ...

Having trouble with dragging a file from one box to another in HTML5. The functionality is not working

Encountering an issue where the image does not display in the left box after dropping it. Here is the sequence of events: Before dragging the image: After dragging the image, it fails to display: The error reported on Chrome is as follows: GET file:/// ...

Having difficulty submitting a form with ajax, while accomplishing the same task effortlessly without ajax

I have been experimenting with submitting a form using ajax to the same .php file. When I submit the form without ajax directly (form action), the database gets updated. However, when I try the same process with ajax, there is no change in the database. H ...

Using jQuery to create clickable images by enclosing them in an `<a>` tag

How can I make each image with a specific class clickable? I would like jQuery to: Retrieve the src attribute of the image. Enclose the image within an a href tag that includes that src URL. .clickable { padding: 20px; border: 1px ...

"Unlock the secret to effortlessly redirecting users to a designated page when they click the browser's back

So I'm facing the challenge of disabling the browser back button on multiple routes and sending requests to the backend is resulting in inconsistent behavior. I don't want to create a multitude of similar API requests each time. Currently, I have ...

Using PHP and AJAX, populate a table based on the selection made from a dropdown

Hello, thank you for taking the time to review my issue. Let me outline the objective. I have successfully implemented two drop-down menus that are populated dynamically from a database. The query retrieves names and phone numbers (with plans to fetch mor ...

What is the purpose of making a "deep copy" when adding this HTML content?

My canvas-like element is constantly changing its contents. I am attempting to execute a function on each change that captures the current content and adds it to another element, creating a history of all changes. window.updateHistory = func ...

Improving the efficiency of ajax/javascript is necessary as the delay in data retrieval is too significant. There must be a more effective approach to this

Utilizing ajax requests to populate modal popup windows with user-filled data has been my current method. These popup windows, designed as div layouts, are controlled by jquery for showing and hiding. However, there seems to be a noticeable delay in this p ...

What steps are needed to switch colors after a loop has been clicked?

I have a loop setup like this: data: { show: false } .test { hight: 10px; background-color: red; } .test2 { hight: 15px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div v-for="value in da ...

Find two separate solutions to the promise

I'm in the process of developing a promise-based route and here is my current promise implementation: const allowEdit = (postid, username) => { return new Promise((resolve) => { db.query(`SELECT * FROM post WHERE id = ${postid} AND usernam ...

The AngularJS array data is not displaying correctly

I am having trouble displaying comments array data in HTML properly. The data appears the same as it is in the comments array. What could be causing this issue? How should I proceed? <ul class="media-list" ng-controller="dishDetailController as menuCt ...

Having trouble getting my app.get calls to work in the new Node Express project

Recently, I kicked off a new project and encountered a perplexing issue - my app.get method simply refuses to be invoked. The site keeps loading indefinitely without any content being displayed. Initially, I copied and pasted the code from another project ...

Sustaining the Status of a Changeable Form Element

To fulfill the requirement of constructing a Form Builder component that generates forms based on JSON data from the backend, I have identified 7 types of input fields that may be encountered: email password select file date input of type text input of ty ...

What are the steps to ensure the equalizer start button functions properly?

I have created an application that mimics the functionality of an equalizer by displaying changes in audio frequencies. Issues with animation arise when you click the "Start" button again. The animation resets and begins from the start. This can be pr ...

Having trouble with Jquery Ajax call in IE8?

I have a dynamic data loading from the database, with each row containing links that perform various actions. Most of them work perfectly fine, but I've noticed an issue with the last one I added – it doesn't seem to be functioning properly on ...

Creating a variable that is named after an existing variable

Creating a new variable with a dynamic name can be tricky. Let's take a look at an example: function preloader(imglist) { var imgs = imglist.split("|"); for (i in imgs) { var img_{i} = new Image; img_{i}.src = imgs[i]; ...

Trouble deploying Firebase Cloud Functions

I am attempting to implement the following two functions: exports.increaseWaitinglistCounters = functions.database .ref('waitinglists/$iid/$uid') .onCreate(async () => { await admin .database() .ref(`waitinglistCounters/$ii ...

What steps should I take to correct the color selection of a button that has been pressed down

Here is the code snippet that I am currently working with: HTTP: <label class="instructions" for="hidden_x"> Insert X: </label> <button type="button" class="button" name="button_x" value="1" id="x_1" onclick="document.getElementById(' ...

How can I retrieve the Azure subscription IDs of the currently logged in user using @azure/msal-angular?

I successfully authenticated a user using @azure/msal-angular and received the id_Token, access_Token and tenant Id. Now I am looking to retrieve the logged in user's azure subscriptions. Is there a way to achieve this through msal or are there any Ja ...

How to showcase base64 encoded images in pug (jade) with node.js

Can anyone help with decoding this mysterious data and displaying the image? I'm using pug as my template engine. Below is the questionable data that needs to be shown as an image: /9j/4AAQSkZJRgABAQEAYABgAAD/4QBaRXhpZgAATU0AKgAAAAgABQ ...and so f ...