Creating Input Fields on the Fly in VueJS

My goal is to dynamically manipulate input fields in real-time.

I found a helpful solution at , which successfully adds and removes fields as needed. However, when attempting to save the input values to the database, the functionality breaks.

Here is the component code I am using:

<div class="form-group" v-for="(input,k) in inputs" :key="k">
  <input type="text" class="form-control" v-model="input.name" />
  <input type="text" class="form-control" v-model="input.party" />
  <span>
    <i
      class="fas fa-minus-circle"
      @click="remove(k)"
      v-show="k || ( !k && inputs.length > 1)"
    ></i>
    <i
      class="fas fa-plus-circle"
      @click="add(k)"
      v-show="k == inputs.length-1"
    ></i>
  </span>
</div>
<button @click="addCandidate">
  Submit
</button>

<script>
  export default {
    data() {
      return {
        inputs: [
          {
            name: "",
            party: ""
          }
        ]
      };
    },
    methods: {
      add(index) {
        this.inputs.push({ name: "", party: "" });
      },
      remove(index) {
        this.inputs.splice(index, 1);
      },
      addCandidate() {
        axios
          .post("/candidates", this.inputs)
          .then(response => {})
          .catch(error => {});
      }
    }
  };
</script>

Upon testing, I consistently encounter a 422 error indicating that the input field is empty.

Answer №1

Don't fuss over Vue, this is an array issue that can be easily resolved. Just remember to use JSON.stringify() before sending the array and then decode it on your server using Laravel. Here's a simple example:

foreach(json_decode($request -> input('my_prop_name ')) as $my_object_in_array)
{
  print_r($my_object_in_array); // This will display your object name/party
}

Your Vue code will work like a charm once you've sorted out this array matter. :)

new Vue({
  el: '#app',

  data () {
    return {
      inputs: [{
        name: '',
        party: ''
      }]
    }
  },

  methods: {
    add () {
      this.inputs.push({
        name: '',
        party: ''
      })
      console.log(this.inputs)
    },

    remove (index) {
      this.inputs.splice(index, 1)
    },

    addCandidate () {
      axios
        .post('/candidates', {
          my_prop_name: JSON.stringify(this.inputs)
        })
        .then(response => {})
        .catch(error => {})
    }
  }
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=app>
  <div class="form-group" v-for="(input,k) in inputs" :key="k">
    <input type="text" class="form-control" v-model="input.name">
    <input type="text" class="form-control" v-model="input.party">
    <span>
      <i class="fas fa-minus-circle" @click="remove(k)" v-show="k || ( !k && inputs.length > 1)">Remove</i>
      <i class="fas fa-plus-circle" @click="add(k)" v-show="k == inputs.length-1">Add fields</i>
    </span>
  </div>
  <button @click="addCandidate">
    Submit
  </button>
</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

Verify if a selection of days using momentjs exceeds 7 days

Is there a way to determine if more than 7 days have been selected on the calendar? I need to disable a button based on this condition. fromDate and toDate are global variables where I store dates from the calendar. Feeling a little confused at the moment ...

A perpetual JavaScript countdown that constantly loops with a delayed response

I'm currently working on an online auction bidding project that involves users placing bids before time runs out. I found a solution on this link. My goal is to run the timer loop continuously. When the timer hits 0, I want the bid button to be disab ...

My page is experiencing delays due to setInterval

Currently, I am delving into the world of Chrome Extension development and am faced with a roadblock in replacing elements on a live chat page. While most of my tasks are running smoothly, the one thing causing issues is the setInterval option that trigger ...

Encountered an error with AngularJS $http.post - Unexpected token F

I've encountered an issue while running my $http.post script and have been searching for a solution without success. Below is the error that appears when I try to run the webpage: XHR finished loading: POST "http://mypage/services/json/DownTimeStartB ...

Exploring the capabilities of a Vue.js component

I am currently facing some challenges while trying to test a Vue.js component. My main issue lies in setting a property for the component and verifying that it has been set correctly. For context, the module has been loaded with exports and the JavaScrip ...

Example of Next.js Authentication - redirecting according to authentication status, encapsulating within other functionalities

I'm currently working on a project using next.js with authentication. The authentication is set up and working, but I'm having trouble displaying the data in my navbar. Originally, I was using firebase for authentication, but now I have it set u ...

Utilizing Windows Azure and restify for node.js Development

I have an azure website with a URL like: . In my server.js file, I have the following code: var restify = require('restify'); function respond(req, res, next) { res.send('hello ' + req.params.name); next(); } var server = restify ...

How can you attach an event handler to an HTML button without disrupting its default behavior?

I am working on enhancing a contact form to include a feature where the submit button becomes disabled for five seconds after it is clicked. This is to prevent accidental repeat submissions from occurring. However, I am facing an issue where disabling the ...

Angular Build Showing Error with Visual Studio Code 'experimentalDecorators' Configuration

Currently experiencing an issue in VSC where all my typescript classes are triggering intellisense and showing a warning that says: "[ts] Experimental support for is a feature that is subject to change in a future build. Set the 'experimentalDeco ...

Ways to retrieve a specific attribute within a detailed JSON reply

I have implemented cloud code in ParseServer - Back4app, which utilizes node.js to send a request for Football API. The axios request returned the following result: { "result": { "get": "teams", "param ...

Redux-form fails to retrieve the value of the SelectField

I'm trying to work with a simple form using react and redux-form. My goal is to gather all the field values from my form and send them to my RESTful API using jQuery ajax. Unfortunately, I've run into an issue where redux-form doesn't seem ...

Using Zombie.js to simulate clicking on a Javascript link

I am currently using Node.js in combination with Zombie.js for web scraping. There are certain pages on which I need to interact with JavaScript links. For instance, consider the following page: http://www.indotrading.com/company/berkat-jaya-electronics. ...

I am experiencing an issue with applying responsiveFontSize() to the new variants in Material UI Typography

I am looking to enhance the subtitles in MUI Typography by adding new variants using Typescript, as outlined in the documentation here. I have defined these new variants in a file named global.d.ts, alongside other customizations: // global.d.ts import * a ...

Automatically closing conditional statement/loop

I'm experiencing an issue with the following if condition: function turnLedOn1(evt) { led.on(); var executed = false; if (!executed) { executed = true; checkin1 = timestamp; alert('checkin1'); } } De ...

Tips for retrieving data from a JSON file

How can I extract two values from JSON data returned by a jQuery/AJAX request and use them in output without necessarily storing them in variables? Here is the jQuery AJAX statement: $.ajax({ url: "proposemarriage_backend.php", type: 'POST&a ...

What is the best way to transfer data from MongoDB to Jade?

Whenever I try to access an object fetched from MongoDB using my client-side JS, I encounter a challenge. Specifically, my goal is to iterate through and utilize the arrays stored within the object. Below is the server-side JS code which effectively retrie ...

What could be causing angularjs to malfunction in this specific scenario?

Recently, I followed a tutorial and implemented the code provided. Inside the angular folder in my libs directory, I have the minified version of Angular JS obtained from https://angularjs.org/. However, the output I am seeing is: {{author.name}} {{autho ...

Retrieve the most recent tweet from a user's timeline using the twit npm package

I need help setting up a discord bot to send notifications for new tweets. Currently, I've implemented T.stream('statuses/filter', { follow : ['798934987978510337'] });, but it's also displaying mentions. Is there a way to o ...

How can VBA be used to link JSON/XML data to Excel cells?

After conducting some research on the internet, I am curious to know if there is a way to import Excel sheet data in JSON or XML format. While there are resources available, none seem to offer clear descriptions for my specific case. My goal is to understa ...

Issues encountered with returning a JSON object while utilizing a webservice (.asmx) in ASP.NET

I am currently utilizing an asp.net web service .asmx for the transportation of JSON data. However, I seem to be encountering issues with the following code: $.ajax({ type: "POST", url: "../../App_Code/jsonWebService/getValue", ...