How can I dynamically append content to the DOM when a user clicks?

On my form, I have an input field that allows users to click an add button and a new input field will appear below it, with the option to repeat this process indefinitely. However, I am facing an issue with adding an input field to the DOM upon a click event.

Initially, I considered using either ngFor or v-for (I am using both, so the solution can involve either). Upon clicking the add button, a counter is incremented and the value is added to an array. Through looping, the inputs are displayed.

let inputs = 0;
addInput() {
  this.inputs++;
  this.criteria.push(this.inputs);
}
<button @click.prevent='addInput'>Add input</button>

<input type='text' value='Default Input'>
<div v-for="input in inputs" v-bind:key="input">
   <input type='text'>
</div>

The functionality is behaving as expected initially - a new input field appears upon clicking the button.

However, the issue arises when I add a second input, input a value, and then add a third input. The second input's value gets reset to blank.

How can I resolve this to ensure that values entered in previous inputs are retained while adding new inputs upon a click event?

Thank you.

Answer №1

By using the v-model directive to bind the input value to an item in the inputs array, you can ensure that the values are retained even when new inputs are added.

let inputs = [];
addInput() {
  this.inputs.push({value: ""});
}
<button @click.prevent='addInput'>Add input</button>

<input type='text' value='Default Input'>
<div v-for="(input, index) in inputs" v-bind:key="index">
   <input v-model="input.value" type='text'>
</div>

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

Is it possible to submit a form through a JavaScript hotkey?

Here's the current code that I'm working with: <select tabindex="2" id="resolvedformsel" name="resolved"> <option selected="selected" value="yes">resolved</option> <option value="no">not resolved</option> ...

Iterate over the object to verify if the field contains an empty array, then output null

Looking for help with handling empty arrays in an object: productDetails: { cislife: [], prime: [] } Is there a way to have null returned instead of an empty array if no values are available? For example, I'd like to determine if either t ...

How can I store the content of a meta tag in a JavaScript variable?

Similar Question: How can I extract data from a meta tag using JavaScript? I have a meta tag that can be customized with content on a specific page, and I'm looking to retrieve this content as a variable in JavaScript. ...

Issue with Flask-Cors in Nuxt with Flask and JWT authentication implementation

I have exhausted all the available solutions to my issue, but I still can't seem to pinpoint the problem. Despite trying every solution out there, nothing seems to be of any help. Every time I make a request, the browser blocks it due to CORS Policy ...

Challenges in integrating a PrimeNG Angular2 component with DynamicDialogRef, as well as the difficulties encountered when attempting to do

I am currently working on implementing a component that utilizes dynamic dialog and requires a direct usage. In the DynamicDialog example, there is a constructor in the car demo list component. constructor(private carService: CarService, public ref: Dynami ...

Customizing the main color scheme in Naive-UI with typescript

I am a beginner with Naive and I want to change the primary color of my app theme to orange. Initially, I used vuestic for this purpose but now I am struggling to implement it. Below is my main.ts file where I had the vuestic override (commented out). Ca ...

Storing a Vue/JS element reference in a constant using Typescript

In my template, I have one form element and one button element: <button type="submit" id="ms_sign_in_submit" ref="submitButton" class="btn btn-lg btn-primary w-100 mb-5"> </button> Wi ...

What is the best way to sort a table by column index using HTML?

I find myself in a situation where I am not well-versed in HTML, Javascript, and CSS. Here is the scenario: <div class="table"> <table class="display-table"> <thead> <tr> ...

Calculate the total sum of a specific property within an array using ES6

My goal is to calculate the total unit value by date and create a new array without duplicate dates. For instance, I want to sum up the values of 2015-12-04 00:01:00. This particular date appears twice in the dataset with values of 5 and 6, resulting in: ...

Encountering a tucked-away issue with the Safari scroll bar?

Encountered an interesting bug where users are unable to scroll down a text nested inside a div. This issue seems to be isolated to Safari, as it doesn't occur in other browsers. I have prepared a sample file to demonstrate the bug and would apprecia ...

Angular validation for password and confirmation password fields

I have been working on implementing password and confirm password validation within an angular project. I recently came across a helpful answer on this thread Confirm password validation in Angular 6 that I tried to follow. Unfortunately, I am encountering ...

Alter the component and then refresh it

I am encountering an issue with a component that has an event handler for a "like" icon. The goal is to allow users to click the like icon, update the database to indicate their liking of the item, and then re-render the component to visually reflect this ...

Update the content of a div and refresh it when a key on the keyboard is pressed

I need to hide the images in a div when I press a key on the keyboard. How can I achieve this? <div> <span role="checkbox" aria-checked="true" tabindex="0"> <img src="checked.gif" role="presentation" alt="" /> ...

Error: JSON input ended unexpectedly and was not caught in the promise block

This code snippet showcases the add to cart functionality, which involves inserting data into a database. Although the database insertion works correctly, an error occurs every time the "add to cart" button is clicked (despite still successfully adding to ...

How can we extract validation data from a function using Ajax and then transfer that information to another Ajax query?

I have an AJAX function that validates a textbox on my page. After validating, I need to perform an action with that value (search in the database and display results in the textbox). However, I also need the validation function for another separate functi ...

Can you explain the distinctions between Vue JS and React JS?

As I delve into learning Vue Js and React Js, my search for a detailed comparison between the two on Google left me unsatisfied. I came across resources answering the singular questions "What is Vue js?" and "What is React Js," but none that directly comp ...

Traverse through the JSON data until a certain condition is satisfied, then proceed to tally the number

Looking to parse a json file containing user data and points. The goal is to loop through the data until the _id matches the userId, then determine the position of that user in the list based on the number of objects. The json file provided below already ...

Error: Unable to set reference. The initial argument includes an undefined value in the 'gender' property of 'Users.ji8A7TkSldfdvieDqGxko9eV3Jy1'

I followed along with a Firebase Web Tutorial on YouTube about adding data to Firebase Database for an account settings tutorial. However, when I tried to implement the code provided, it didn't work. Can anyone offer any assistance? // Code snippet fo ...

What causes a React Ref callback to be invoked multiple times during the initial loading of a page?

To find more information, please visit this URL within the React DOCS. You can also access a version of this code here. I acknowledge that it is recommended to use the useCallback hook in a Functional React Component to create a ref callback according to ...

Tips for avoiding HTML <tags> in the document.write function

I am trying to paint the actual HTML code within a tag using JavaScript but escaping it doesn't seem to be working. function displayHTMLString(n){ document.write("'<table>'"); for (i in range(0,n)){ ...