Using Vue.js to dynamically append varying inputs upon user interaction

When I select an option, I want to display different types of inputs based on the selected option.

For Example:

  1. Select input -> show input fields
  2. Select textarea -> show text areas
  3. Select boolean -> show radio buttons

The Code

This is where I choose my input types,

Note: @change="inputType"

<div v-for="(index, a) in variationParents" :key="a">
<el-input placeholder="Please input your variation name" v-model="index.name" class="input-with-select">
    <el-select @change="inputType" v-model="index.type" slot="prepend" placeholder="Select">
        <el-option label="Text" value="input"></el-option>
        <el-option label="Text Area" value="textarea"></el-option>
        <el-option label="Boolean" value="boolean"></el-option>
    </el-select>
</el-input>
</div>

The Script

Note: I am using jQuery instead of vueJs for this function just to test and make sure that I'm getting the correct value from my select options.

methods: {
  inputType: function(value) {
    $('.show').html('')
    if(value == 'input') {
      $('.show').html(value)
    } else if(value == 'textarea') {
      $('.show').html(value)
    } else if(value == 'boolean') {
      $('.show').html(value)
    }
  },
}

The HTML Section

This section should return different types of inputs, currently it only has a static input field. It should be linked to the function's if statements to print the related type of inputs.

<div class="show"></div>  // This DIV was used solely for testing my function values
<el-col :span="9" style="margin-top:15px;display:none;">
    <div v-for="(indexx, b) in variationChilds" :key="b">
        <!-- child's -->
        <el-input v-model="indexx.name" placeholder="Please input your variation value" class="input-with-select">
            <el-button slot="append"  @click="addChild(b)"  type="success" icon="el-icon-plus"></el-button>
            <el-button slot="append" @click="removeChild(b)" v-show="b || (!b == variationChilds.length > 1)" type="danger" icon="el-icon-delete"></el-button>
        </el-input>
    </div>
</el-col>

Any thoughts or suggestions?

Answer №1

Ensure to include the necessary input elements within your div tag along with conditions based on specific criteria, as demonstrated in the code snippet below

<div class="display">
   <input type="text" v-if="data.type == 'text'">
   <textarea v-if="data.type == 'textarea'">
   <input type="checkbox" v-if="data.type == 'boolean'">
</div> 

Answer №2

Opt for utilizing this.index.type directly instead of passing the value in inputType.

methods: {
  inputType: function() {
    const value = this.index.type;
    $('.show').html('')
    if(value == 'input') {
      $('.show').html(value)
    } else if(value == 'textarea') {
      $('.show').html(value)
    } else if(value == 'boolean') {
      $('.show').html(value)
    }
  },
}

Answer №3

Issue Resolved

To address the problem, I utilized 3 separate div elements with different conditions specified within them, such as

<div v-if="selecteVariation == 'input'">
, each containing distinct input types.

Code snippet

data(){
  return {
     selecteVariation: '',
  }
},
methods: {
  inputType: function(value) {
     this.selecteVariation = value
  }
}

I trust that this solution may prove beneficial to others facing similar challenges.

Answer №4

Why use an @click function handler when the v-model is already present in the select options? You can simplify your code and eliminate the need for jQuery by structuring it like this:

<el-input placeholder="Please input your variation name" v-model="index.name" class="input-with-select">
    <el-select v-model="index.type" slot="prepend" placeholder="Select">
        <el-option label="Text" value="input"></el-option>
        <el-option label="Text Area" value="textarea"></el-option>
        <el-option label="Boolean" value="boolean"></el-option>
    </el-select>
</el-input>
<div>
   <input type="text" v-if="index.type == 'input'">
   <textarea v-if="index.type == 'textarea'">
   <input type="radio" v-if="index.type == 'boolean'">
</div> 

You can then initialize index.type inside the data() method:

data() {
  return{
    index.type = ''
  }
}

This way, the input field will initially not display any specific type of input.

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

Modify the structure of the JSON string

My JSON string is structured like this: [ { "queryResult": { "A": "12-04-2014", "B": 1 } }, { "queryResult": { "A": "13-04-2014", "B": 2 } }, { "qu ...

Using AngularJS, you can display repeated elements in a single textarea by utilizing

--> I want to be able to input data into a textarea using just one textarea element. --> The reason for this is so that when the data in MySQL is updated, I can type new data in the textarea while still keeping the existing data. I have tried using ng-re ...

The use of custom loaders alongside ts-node allows for more flexibility

Is it possible to utilize ts-node with a custom loader? The documentation only mentions enabling esm compatibility. ts-node --esm my-file.ts I am attempting to implement a custom loader for testing an ESM module, but I prefer not to rely on node for compi ...

I need to fetch data from mongoDB by allowing the user to input a name into a search field, and then retrieve all documents that correspond to that search term

I am currently able to query the database by finding a specific key:value pair in the documents. However, I would like to enhance this functionality by allowing users to input their own search criteria as an argument in the function. Right now, I have hard ...

Step-by-step guide to implementing a month and year date-picker in Mozilla Firefox

I'm looking to create input fields where users can add the month and year. I tried using the code below, but unfortunately Mozilla Firefox doesn't support it. <input type="month" id="start" name="start"> Does ...

What is the method to retrieve the selected value from a drop-down menu that is connected to JSON keys?

I am just starting to learn AngularJS and I need help with binding column names (keys from key-value pairs) to a select list. I want to be able to retrieve the key name when the selection in the select list is changed. The select list displays: name, snip ...

Remove background image when input form field is in focus

I am currently experimenting with the following approach: $('input').on('click focusin', function() { $('.required').hide(); }); However, it appears that this logic is not functioning as intended. Here is an ...

What is the best way to interact with Redis without using any external modules?

I am curious about the communication process between the node redis wrapper and the RESP (REdis Serialization Protocol) database. Here is a simple example: const redis = function(uri) { this.client = '' // How do we establish a connection wit ...

Issue with AngularJS directives - encountering a problem with the property 'compile' being undefined

Just starting out with AngularJS and attempting to make a basic directive. Unfortunately, the code is throwing a TypeError: Cannot read property 'compile' of undefined. Any advice or suggestions would be greatly welcomed. JS var xx = angular.mo ...

Unlock the potential of Vue custom props within the asyncData function in your nuxtjs project!

I have a special function in my project that serves as a plugin import Vue from 'vue' function duplicateText(text) { var input = document.createElement('input'); input.setAttribute('value', text); document.body.a ...

AngularJS Toggle Directive tutorial: Building a toggle directive in Angular

I'm attempting to achieve a similar effect as demonstrated in this Stack Overflow post, but within the context of AngularJS. The goal is to trigger a 180-degree rotation animation on a button when it's clicked – counterclockwise if active and c ...

Mysterious occurrences always seem to unfold whenever I implement passport for user authentication in my Node.js and Express applications

At first, I wrote the following code snippet to define LocalStrategy: passport.use( 'local-login', new LocalStrategy({ usernameField:'username', passwordField: 'password', passReqtoCallback: tr ...

Tips for optimizing performance by preloading external CSS and JavaScript files from a third-party source in a ReactJS project with webpack

Is there a method similar to using ProvidePlugin for preloading jQuery that can be used to preload third-party CSS and JS files without using import in the entry JS file? The reason I am interested in preloading these files is because I encountered an err ...

Husky 5: The Ultimate Gitignore Manager

Last week, a new version of Husky was released, known as Husky 5. I came across an interesting article discussing the features and updates in this release that can be found here. Upon migrating to Husky 5 (), I discovered a new directory named .husky with ...

What is the best way to create a Laravel object for use in JavaScript in a Laravel Blade?

please add description hereI am looking to obtain an object with this particular style var zoz2= { "11-30--0001": "<a href=\"https:\/\/www.dooz.ps\/p\/107229\" >\u0625\u0637\u0644\u0627& ...

Best practices for locating unique symbols within a string and organizing them into an array using JavaScript

Here is an example string: "/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>" The characters A, B, C, and so on are variables, and their count is not fixed. Can you determine how many ...

Tips on setting a singular optional parameter value while invoking a function

Here is a sample function definition: function myFunc( id: string, optionalParamOne?: number, optionalParamTwo?: string ) { console.log(optionalParamTwo); } If I want to call this function and only provide the id and optionalParamTwo, without need ...

Utilize the Google Drive API to easily upload an Excel file

I'm encountering an issue with the Google Drive API. I've been attempting to upload an Excel file using this API, but haven't had any success. I even tried following the instructions in the Google API documentation without luck. Below is a ...

Reacting with Angulatory: Response heads are not being transferred in applications

I'm facing an issue where the cookie containing my authentication token doesn't get passed along with my requests. After authenticating in Chrome, the response sets the cookie correctly, but it's not included in subsequent requests. This is ...

What is the proper method for utilizing assignments instead of simply assigning values directly?

In the process of developing a markdown editor, I am currently focusing on the functionality of the B (bold) button which needs to toggle. It's important to mention that I am utilizing this library to handle highlighted text in a textarea. Below is t ...