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
  }
}

https://i.sstatic.net/9DYxl.png

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

Passing a Typescript object as a parameter in a function call

modifications: { babelSetup?: TransformationModifier<babel.Configuration>, } = {} While examining some code in a React project, I came across the above snippet that is passed as an argument to a function. As far as I can tell, the modifications p ...

Scrolling through a lengthy table without affecting the overall window scroll

I currently have a situation where I have a table positioned below several div elements: <div></div>...<div></div> <div id="tablecontent"> <table>...</table> </div> My goal is to make the table scrollable ...

Curious as to why JavaScript restricts the use of two variables entering at the same time

Currently, I am tackling an Ajax-php livesearch programming challenge. I am facing an issue where JavaScript is unable to receive the values of 2 parameters that I want to input in HTML input boxes. Any idea why this might be happening? This is my HTML co ...

Creating a new variable and then trying to access its value (which has not been defined)

I'm encountering an issue while trying to define a const variable called filteredRecipes and use it to setState. The problem is that the console is showing an error message saying that filteredRecipes is undefined, Uncaught ReferenceError: filteredRe ...

Postman's ability to capture elements that meet specific criteria set by another element

Here is the output of my response code: [ { "id": 364, "siteName": "FX21 - PortA", }, { "id": 364, "siteName": "FX21 - PortB", }, { "id": 370, "siteName": "FX05 - ER", }, I'm tr ...

Utilizing a Single Background Image Across Several Div Elements

Let me illustrate my question using a sequence of images. The div container is set to display the background image as follows: In addition, there will be tile-shaped divs layered on top of the image: I aim to have the background image visible only withi ...

What is the best way to utilize a promise for a singular variable?

In my code, I have a requirement where I need to make two HTTP requests. The second request is dependent on information retrieved from the first request. Initially, the first request sets the variable 'amount' which is later used in the second re ...

Tips for integrating external JavaScript libraries and stylesheets into a widget

I am currently working on developing a custom Javascript widget that requires users to insert specific lines of code into their web pages. This code will then dynamically add an externally hosted javascript file, allowing me to inject HTML content onto the ...

What methods should I use to modify the upcoming array of objects?

I have been struggling with this exercise for about an hour now, and I can't figure it out. Can someone please help me with this? Here is the array that I retrieved from the database: View Base Array Image let data = [ { "name": "October : 2019", "u ...

Comparing Fetch and Axios: Which is Better?

Currently delving into the realms of axios and the fetch API, I am experimenting with sending requests using both methods. Here is an example of a POST request using the fetch API: let response = await fetch('https://online.yoco.com/v1/charges/&ap ...

Guide on how to have two controllers execute identical tasks in Angular while modifying the appearance of the website

Trying to recreate Google's homepage functionality using Angular has been challenging for me. Despite watching Egghead videos and studying the API extensively, I couldn't find a specific example for this behavior. Here's what I aim to achiev ...

JavaScript: the battle between anonymous and direct function invocation

Here is an interesting observation: when I assign an anonymous function to the onreadystatechange variable, everything works fine. However, if I try to assign a named function to this variable, it does not work as expected. <script language="Javascrip ...

Can you please highlight parts of the text and provide dialogue with additional information?

I am currently enhancing my blog and looking for a way to implement JavaScript functionality that will help highlight specific parts of my text and provide additional information, like: I am currently working on my laptop When the user clicks on "lapto ...

Having trouble with uploading files through axios in VueJS 2 and Strapi

Here is the code snippet for my interface: Apply.vue: <template> <div> <div class="send-background"> <form action=""> <div class="send-form-child"> <h3>{{jobin ...

VueJS: The background image is mistakenly displayed in all sibling components instead of only the component where the image was uploaded

Check out this interactive demo on CodeSandbox where the child component includes an image file input. The uploaded file is displayed as the background image of the input's parent wrapper div using reader.readAsDataURL(file). However, the issue aris ...

Struggling with smoothly transitioning an image into view using CSS and JavaScript

I'm currently experimenting with creating a cool effect on my website where an image fades in and moves up as the user scrolls it into view. I've included the code I have so far below, but unfortunately, I keep getting a 404 error when trying to ...

transferring data from JavaScript to PHP variables

Currently, I am working on a project that involves using ajax to access the database asynchronously. The value retrieved is stored in a JavaScript variable like this: var content=xmlhttp.responseText; My next step is to pass this value to the PHP module ...

Encoding a two-dimensional array into JSON format

In my PHP script, I am querying a database and formatting the results as JSON: $query = mysql_query($sql); $rows = mysql_num_rows($query); $data['course_num']=$rows; $data['course_data'] = array(); while ($fetch = mysql_fetch_assoc($q ...

How do prototype, the $.extend method, and the concept of "return this" all connect with each other?

I've been assigned a legacy project, and I find myself puzzled by the purpose of this code. define(['jquery', 'components/BaseComponent', 'bootstrap'], function( $, BaseComponent, bootstrap ) { 'use strict&a ...

How can I prevent a browser from allowing users to select an image tag?

I'm dealing with an issue on my webpage where I have an image that is inadvertently picking up mouse clicks, causing the browser to perform drag and drop actions or highlight the image when clicked. I really need to use the mousedown event for somethi ...