Adding data to a Vue.JS array from an HTML source

I'm facing a challenge with my assignment where I am struggling to input data from HTML into the VUE.JS array. I have created this form, and now I need assistance in updating the Students array in Vue.js when a user completes the form and clicks on the "Add a new student" button. I am unsure about how to update the array upon button click. Below is the complete code. Any help would be greatly appreciated! Also, I need guidance on making the delete button functional so that it removes a row when clicked.

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style type="text/css">
        <!--
        /* @import url("css/tablestyle.css");
        @import url("css/form.css"); */
        -->
    </style>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ee8ebfbdeacb0a8b0afaa">[email protected]</a>/dist/vue.js"></script>
    <style>
        .agreeGreen {
            color: Green;
        }
        .agreeRed {
            color: Red;
        }
    </style>
</head>
...

Answer №1

To make your code work in Vue format, you need to utilize v-model for two-way data binding and then trigger a @click event on button click to retrieve the values of all fields bound with v-model and add this data to the students array.

I have created a simple demo using a single input field. The same approach can be applied to other fields as well.

Give this a try:

new Vue({
  el: '#app',
  data: {
    student: {
      name: null
    },
    students: [{
      name: "Mike",
    }, {
      name: "Emma",
    }, {
      name: "Emily",
    }],
  },
  methods: {
    addStudent() {
      if (this.student.name) {
        this.students.push({name: this.student.name})
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <form>
    <div class="form-group">
      <label for="name">Student Name:</label><input id="name" v-model="student.name" type="text">
    </div><br>
    <button type="button" @click="addStudent">Add a new student</button>
  </form>

  <h2>Students list</h2>
  <hr>

  <table>
    <thead>
      <th>Name</th>
    </thead>
    <tbody>
      <tr v-for="student in students">
        <td>{{student.name}}</td>
        <td><a href="">Delete</a></td>
      </tr>
    </tbody>
  </table>
</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

Syntax for chained arrow functions

const retrieveData = link => dispatcher => { // ... } export const fetchInfo = searchTerm => (dispatcher) => { return dispatcher(retrieveData(searchTerm)); }; What role does dispatcher play in the retrieveData function? Is link the only p ...

Stopping errors are a common occurrence in synchronous AJAX

I recently encountered an issue with my AJAX request setup. In the success callback function, I called a new function to render Google links and made another AJAX call. To address some performance concerns, I attempted to change these asynchronous calls t ...

End of container Bootstrap 4 row with two columns at the edge

I'm currently working on an angular project with bootstrap 4. Within the container, there are two rows. I specifically want one row to always be positioned at the bottom of the container. Despite trying methods like justify-content: flex-end;, botto ...

Creating an executable JAR for your Next.js application: A step-by-step guide

Is there a way to ensure that my Next.js file can run seamlessly on any computer without the need for reinstallation of all modules? In my folder, nextjs-node, I have the following subfolders: components lib public node_modules page style package.json I ...

ui-grid row size set to automatically adjust using rowHeight : 'auto'

Has anyone else experienced this strange behavior with ui-grid? When I set the rowHeight to auto, each cell in the same row ends up with different heights. One of the cells contains multiline data, which seems to be causing issues for ui-grid. I've ev ...

What causes axios to return a z_buf_error?

I've encountered an issue with axios returning an error cause: Error: unexpected end of file at BrotliDecoder.zlibOnError [as onerror] (node:zlib:189:17) { errno: -5, code: 'Z_BUF_ERROR' I'm puzzled as to why this functio ...

Displaying Buffered Geometry in React-Three-Fiber

I am currently attempting to implement the example found at in a React-Three-Fiber environment. My code is encountering several issues. Firstly, I am consistently receiving the following warning in Chrome: [.WebGL-0x26d30384f700] GL_INVALID_ENUM: Enum i ...

Is there a intentional way to cause my node.js server to crash?

Is there a way to intentionally crash my node.js server? I want to trigger this action when specific fatal errors occur in order to immediately bring them to my attention for fixing. I came across a post about this topic here, but I am not interested in u ...

Encountering a Issue with POST Method in AngularJS Calling .NET WebAPI

I am currently facing a challenge with my AngularJS and .NET WebAPI integration. While I can retrieve content or objects successfully through the WebAPI, I am encountering difficulties when attempting to POST data. When trying to post the content, I recei ...

Altering the input type of a cloned element in Internet Explorer results in the loss of the value

When I have checkbox inputs displayed in a modal with preset value attributes, upon clicking "OK", I clone them and change their input types to hidden, then append them to a div in the document body. However, when trying to retrieve their values using jQue ...

Personalizing a Doughnut Graph

Currently in the process of creating a donut chart I am looking to achieve a design similar to the image below, where the values are displayed within the colored segments import DonutChart from 'react-d3-donut'; let data = [{ count ...

JSON did not anticipate the presence of token at the beginning position

I am currently facing an issue with my JavaScript files. The first file performs a GET request to an API and outputs the results to a JSON file. However, when I try to parse this JSON file in another JS file, I encounter errors. SyntaxError: Unexpected to ...

Optimally align child divs within container in row and column layouts

Looking for a way to dynamically adjust div sizes based on available space within the parent container to minimize white space. Hoping for a solution that can accommodate fluctuations in the number of divs over time. The goal is to reduce white space as m ...

JavaScript function for dividing the table into months

I am looking to organize a table where the data is automatically generated, but I want to separate it by months in descending order. Each table should be grouped by the month name and year they correspond to. To assist with understanding my request, I hav ...

What steps do I need to take to successfully integrate Font Awesome 5 with React?

Here is an interesting scenario: the initial icon is displayed, but it fails to update when the class changes. const Circle = ({ filled, onClick }) => { const className = filled ? 'fas fa-circle' : 'far fa-circle'; return ( ...

Adding metadata fields to an existing Markdown file within TinaCMS

Is it feasible to enhance a Markdown file using TinaCMS by introducing new frontmatter fields? Instead of generating a brand new Markdown file, my goal is to modify the current one by appending new frontmatter fields. Currently, I am able to modify a sin ...

Even when hovering out, jQuery maintains its hover styles

I have a jQuery script that displays a content box when hovering over a button, with the button's hover class activated. The goal is to maintain the hover styles on the button even when the mouse hovers inside the displayed content box. However, if th ...

information not adhering to the text field

I'm having some trouble with Vue as I try to bind the result to a textarea: <textarea class="form-control" id="test" rows="6" v-model="test"></textarea> data: { test: '' } axios({ method: 'po ...

Are you ready to maximize your Selenium expertise?

After searching diligently, I was unable to locate a solution to the question at hand. My goal is to utilize Selenium to click on a button; however, the button ID changes dynamically after each press. Ideally, I would like to be able to click the button us ...

Customize the appearance of each element in ng-repeat individually

In my code, I have implemented an ng-repeat. Each alternate div inside the ng-repeat is supposed to have a different border-color, which is achieved by using the following structure: <div ng-repeat="channel in channelList"> <div ng-style="get ...