Guide on replacing placeholders in a text with input fields and connecting them with v-model in Vue.js

I am currently working on creating an exam page that features fill in the gap type questions. These questions have placeholders where students need to insert the correct words or phrases. The questions are fetched via an ajax request and consist of simple text with specific gaps for responses. Each question can contain one or more fill in the gap sections.

For example:

The cats are {black} and {white}, they also like {brown}.

To convert this, I am utilizing Vue.js by replacing the placeholders with input fields:

<p>The cats are <input type='text' v-model='gap1'> and <input type='text' v-model='gap2'>, they also like <input type='text' v-model='gap3'>
.

Currently, I have implemented a computed method in my component to dynamically add these input fields:

computed: {
    addGapsField () {
        let regex = /\{.*?\}/g
        let match = ''
        let updatedText = this.question

        // loop through each match
        while((match = regex.exec(updatedText)) !== null) {
            updatedText = updatedText.replace(match[0],"<input type='text'>")
        }
        return updatedText 
    }
}

I am exploring methods to bind v-model to these dynamically generated input fields. If not v-model, I am open to other suggestions within Vue.js as well.

Answer №1

If you want to break down your question and loop through it using a v-for in the template (remember to utilize <span> for inline display).

new Vue({
  el: "#app",
  data: {
    question: "The apples are {green} or {red}, some times {yellow}.",
    gaps: [],
    last: ''
  },
  computed: {
    addGapsField () {
      let reg = /\{.*?\}/g
      let text = this.question.split(reg)
      text.forEach((part, i) => {
        this.gaps.push('gap' + (i+1))
      })
      this.last = text.pop()
      return text
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="app">
  <span v-for="(part, index) in addGapsField">
    {{ part }}<input v-model="gaps[index]">
  </span>
  <span>{{ last }}</span>
</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

Issues with PHP ajax causing database insertion failure

Here is the code for making an AJAX request: AJAX var date = new Date().toLocaleTimeString(); var text=this.value; var id=1; $.ajax({ type: "GET", url: "StoreMessages.php" , data: { room: id, msg:text, sendat:date } }); PHP Code if(isset($_GET['r ...

Issue with Angular modal text boxes failing to populate using ngModel

I am facing an issue with populating data in a modal when a table row is clicked. The table contains TV show data and uses dir-paginate/ng-repeat to display the information. However, when I click on a row to edit the show, the ng-model data does not load i ...

Having trouble with d3 / svg layering when introducing new nodes overtime

Struggling with a frustrating issue on my d3 force directed map project. Initially, I render the necessary nodes and links, then periodically check for updates through AJAX. The problem arises when adding new nodes and links – they appear over existing c ...

Warning: Unhandled promise rejection - The type error occurred because the property 'close' of the object is undefined

I am currently configuring node.js in order to test my JavaScript codes using the Jest JavaScript testing framework. Can anyone spot what I might have done incorrectly? package.json file { "name": "institute-jest", "version&quo ...

How should v-select, item-text, and item-value be correctly utilized?

When I make an API call, the response is returned. https://i.sstatic.net/AsFzu.png from another perspective. https://i.sstatic.net/T4vqa.png I store the result of the API call in a variable called result = [];. To create a dropdown list, I use v-select ...

Leveraging the node CLI tool as a library for trimming MP3 files (trimp3

I recently came across a fantastic library that I am interested in using for my nodejs project: https://github.com/kyr0/trimp3 The only issue is that it functions as a cli tool, and I would like to integrate it seamlessly into my codebase as a library. D ...

Add a file to your Google Drive by utilizing AJAX with Google Apps Script

Currently, I am working on a code to upload an image file to Google Drive using app script. I have encountered an issue where I am unable to retrieve the file from the request.parameters. I attempted to use formData as well, but it did not resolve the pro ...

Express is unable to locate the specified property

Here is my controller code snippet: exports.showit = function(req, res){ res.render('showpost', { title: req.post.title, post: req.post }) } In my post model, I have included title and name objects: title: {type : String, default : &apos ...

retrieving the configuration settings from my customized service

When attempting to access my custom service within its config property in order to inject an HTTP interceptor, I am encountering the following issue: angular .module("common.services") .factory("redirectService", [" ...

"Utilizing GroupBy and Sum functions for data aggregation in Prisma

I am currently working with a Prisma schema designed for a MongoDB database model orders { id String @id @default(auto()) @map("_id") @db.ObjectId totalAmount Int createdAt DateTime @db.Date } My ...

What is the best way to create a series of synchronous HTTP requests using $http in AngularJS?

I am facing the challenge of uploading a list of video objects with different attributes and links. Currently, I have set up a loop to go through each object in the list and upload the videos one by one since the service I am using does not support multipl ...

Exploring the world of components and experimenting with nesting them

As I am delving into Vue.js, I am attempting to nest two components without diving straight into cli or webpack. My approach involves avoiding import/export statements. However, upon inspecting the browser's console, I encountered the following warnin ...

Is there a way to arrange an array based on the initial value?

In my array, I have a mixture of strings and arrays. Each string corresponds to the array next to it. For example, the string 789 is associated with the array ['111A', '222B', '333C']. My goal is to sort based on the strings w ...

Personalizing the display of Vuetify pagination controls

I've implemented the vuetify pagination with the following code snippet: <v-pagination v-model="page" :length="n" total-visible="7" ></v-pagination> When n is greater than 7, if you're on the first few pages, it will display b ...

What could be causing my node.js to fail in producing a true result within the return statement?

I've encountered an issue with VS code where the return true command is not displaying anything in my terminal, while console.log(map[arr2[j]]) successfully returns true. I'm unsure if this problem lies with node or my terminal. How can I ensure ...

Is there a way to add a scrollbar to the ChartJS tooltip to avoid data

I'm currently working on a chartJS project where I have a callback function to display data in tooltips. However, as the data increases, the overflow section of the tooltip gets hidden from the canvas. Is there a solution to prevent this overflow and ...

How can I prevent scrolling in a Vue mobile menu?

In this scenario, the toggle for the menu is controlled by a checkbox with the id "check" below. I attempted to bind v-bind:class="[{'antiscroll': checkboxValue}]" to the body in HTML, and also in the main App.vue file, but it did not work as exp ...

What is the method for inserting a clickable link into a data-image line of code using CSS3?

Recently, I delved into the world of CSS and am still getting the hang of it, Below is a snippet of code that I have been working on, <div id='ninja-slider'> <ul> <li> <div data-image="images/md/1.j ...

Getting data from a wordpress database using javascript

After setting up a table named inspirationWall in my database with id and Visit_Count as INT, I inserted a row with id=1 and Visit_Count = 2. Now, attempting to fetch the Visit_Count value in WordPress and show it in an alert for testing purposes. I have ...

Retrieving Vue component properties as a data type

I'm facing a dilemma with my Vue components. I want to extract the props from one component and use them as a type instead of a value in another component. Specifically, I have a component where I need to take in an array of props from a different com ...