Combining user input data using JavaScript and Vue.js

I am working on a form using Vue.js and I want to combine the data from the input fields upon submission. I have been struggling to achieve this and created a jsfiddle to showcase my attempt.

In my form, I have three Vue components for each of the input fields. The first component is a dropdown list that I want to change to an input text field for custom options.

Whenever I try to concatenate the data from all three fields, I encounter an undefined error in the JavaScript code.

new Vue({
    el: '#product_id',
    data: {
        selected: '1',
        options: [
            { text: 'Product 1', id: '1', value: '1' },
            { text: 'Product 2', id: '2', value: '2' },
            { text: 'Product 3', id: '3', value: '3' },
            { text: 'Product 4', id: '4', value: '4' },
            { text: 'Custom', id: '5', value: '' }
        ],
        product_i: '',
        resetKey: 0,
    },
    methods:{
        updateComponent(){
            this.resetKey += 1;
            console.log(this.resetKey);
            console.log('test');
        }
    },
}),

new Vue({
    el: "#product_name",
    data: {
        product_n: '',
    }
});

new Vue({
    el: "#product_price",
    data: {
        product_p: '',
    }
});


function combine_product_datas() {
    var id = document.getElementById('input1').value;
    var name = document.getElementById('input2').value;
    var price = document.getElementById('input3').value;
        document.getElementById('joint').value = id + '.' + name + '/' + price;
        alert(document.getElementById('joint').value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div class="row">
  <div id="product_id">    
    <div :key="resetKey">
      <small>Product id</small>
      <div v-if="selected != ''">
        <select v-model="selected">
          <option v-for="option in options" v-bind:value="option.value">
            {{ option.text }}
          </option>
        </select>
      </div>
      <br>                      
      <div v-else>
        <input id="id" v-model="product_i" value="" type="text" placeholder="Add your product">
        <button v-on:click="updateComponent">Reset</button>
      </div>
  </div>
</div>
<br>                      
<div id="product_name">
  <div>
    <div>
        <small>Product name</small><br>
        <input id="name" v-model="product_n" type="text">
    </div>
  </div>
</div>
<br>                      
<div id="product_price">
  <div>
    <div>
      <small>Product price</small><br>
      <input id="price" v-model="product_p" type="text">
    </div>
  </div>
</div>
<br>                       
<div>
  <div>
    <button type="submit" onclick="combine_product_datas();">Combine datas</button>
  </div>
</div>
<br>                      
<input type="hidden" id="joint">
<br>                      
</div>

Answer №1

Upon reviewing the code, it seems unnecessary to have three separate Vue instances. Instead, you can consolidate everything under a single wrapper and utilize just one Vue instance. By doing so, you can include the javascript function within that sole instance and eliminate the need for document selectors to retrieve the combined value. The updated code looks like this (revised js fiddle here):

new Vue({
        el: '#app',
        data: {
            selected: '1',
            options: [
                { text: 'Product 1', id: '1', value: '1' },
                { text: 'Product 2', id: '2', value: '2' },
                { text: 'Product 3', id: '3', value: '3' },
                { text: 'Product 4', id: '4', value: '4' },
                { text: 'Custom', id: '5', value: '' }
            ],
            product_i: '',
            resetKey: 0,
            product_n: '',
          product_p: ''
        },
        methods:{
          updateComponent(){
            this.resetKey += 1;
            console.log(this.resetKey);
            console.log('test');
          },
          combineData() {
          const { product_i, product_n, product_p } = this;
            alert(`id: ${product_i}, name: ${product_n}, price: ${product_p}`)
          }
        },
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <small>Product id</small>
  
  <div v-if="selected != ''">
    <select v-model="selected">
      <option v-for="option in options" v-bind:value="option.value">
        {{ option.text }}
      </option>
    </select>
  </div> 
  
  <div v-else>
    <input id="id" v-model="product_i" value="" type="text" placeholder="Add your product">
    <button @click="updateComponent">Reset</button>
  </div>
  
  <div>
    <small>Product name</small><br>
    <input id="name" v-model="product_n" type="text">
  </div>

  <div>
    <small>Product price</small><br>
    <input id="price" v-model="product_p" type="text">
  </div>            

 <button type="submit" @click="combineData()">Combine data</button>
  <span :value="combined"></span>
                   
  <input type="hidden" id="joint">

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

Discover past stock prices on Yahoo Finance

I'm stuck on tweaking a functioning jfiddle example that I have. Can anyone help me with this two-part question regarding the jfiddle: http://jsfiddle.net/maxmillien/qPVSy/ Part 1) Is there a way to clear the search each time a new search is performe ...

Is it possible to utilize a JavaScript variable as a node in a JSON stringification request?

After successfully retrieving data from the Bungie API previously, I am now facing a challenge in reading a specific JSON file. http://prntscr.com/k3tin3 I'm currently stuck on how to extract a node from the JSON and then utilize it to request charac ...

The PKIJS digital signature does not align with the verification process

Explore the code snippet below const data = await Deno.readFile("./README.md"); const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate; const privateKey = (await loadPEM("./playground/domain-pk ...

Is it possible to generate a component dynamically using a string template?

I have a Component called "CDataTable" that renders columns in a for loop. Inside the loop, there is a template: <template v-if="typeof col.template !== 'undefined'" #body="{data}"> <component :is="compile(co ...

What is the process for modifying the characteristics of an RMWC Component?

How can I dynamically change the icon attribute in my RMWC Button element when an onClick event occurs? <Button outlined icon={<CircularProgress />} onClick={(e)=> { // e.currentTarget.icon = ''; // console.log(e.c ...

The Datatable feature is malfunctioning, unable to function properly with Javascript and JQuery

As a novice in the world of jquery/javascript, I find myself struggling with what may seem like an obvious issue. Despite following tutorials closely (the code for the problematic section can be found at jsfiddle.net/wqbd6qeL), I am unable to get it to wor ...

Repeating the process of running a function multiple times

export default function MyQuestions() { const router = useRouter(); const [auth, setAuth] = useState(false); const checkAuth = async () => { const loggedInUsername = await getUsername(); if (router.query.username === loggedInUsername) re ...

What is the best way to integrate JavaScript into an Express Handlebars template using partials?

In my current project, I have utilized the following handlebars template (located under views/layouts/main.handlebars): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{{title}}</title> ...

Determine whether the user has scrolled past a specific threshold

Is there a way to display the button with the id backtotop only when the user has scrolled more than 250 pixels? This is my code: <template> <div> <button v-if="checkScroll" class="goTop" @click="backToT ...

Is it necessary to make multiple calls following a successful AJAX request?

Here is an AJAX call I am setting up. The first step is to hit the endpoint dofirstthing.do. Once that is successful, the next step is to make another call with "param1" as the query parameter. Now, my question is - how can I make a third call with "param ...

What is the most efficient method for managing axios errors in Laravel and Vue.js?

Currently, I am developing spa web applications using Laravel as the backend and Vue.js as the frontend framework. For authentication with API, I am utilizing Laravel Passport, and for managing my application state, I am using Vuex. Initially, I created A ...

Use the knockout textInput plugin in combination with the maskedinput plugin

Is there a simple way to use data-bind="textInput: aProperty" and apply an input mask or automatic formatting while the user is typing? Although using the masked input plugin somewhat works, it results in losing the real-time updates that Knockout's ...

Leverage JSON data to generate individual elements, rows, and columns for every object within the array

Just starting out with JavaScript and struggling a bit. We need to fetch data from this URL: and then manipulate the data to create new rows (tr) and columns (td) for each game without altering the HTML file. The desired outcome should resemble this: I&a ...

The ngOnChanges method fails to exhibit the anticipated modifications in a variable

Trying to grasp the concept of the ngOnChanges() callback, I created an example below. Despite having values for the attributes title and content in the Post interface during compile time, I do not see any logs from ngOnChanges. Please advise on the corre ...

Guide to seamlessly navigating to an element using a hash in NuxtJS

My aim is to create a smooth scrolling anchor link menu using Nuxt.js, where the user can click on a link and be directed to the corresponding page section. However, I'm facing a dilemma as there are multiple approaches to achieve this functionality, ...

Unable to locate the root element for mounting the component in Cypress with React

I am currently testing my react app, which was created using create-react-app, with the help of cypress. Unfortunately, I encountered an error that looks like this: https://i.stack.imgur.com/xlwbo.png The error seems to be related to trying to fetch an ...

Having trouble with the ajax cache not working properly when trying to load an image

I am attempting to dynamically load an image from the server every time a button is clicked using a GET request. However, I am facing an issue where the cached image is being loaded instead of the latest version. Below is the code I am currently using: & ...

When utilizing jQuery in HTML, the Marquee will bounce back upon reaching the end

My issue is that when I use a regular marquee, the text simply goes to the end and does not bounce back to the start as soon as it reaches the end of the div. Instead of using a normal marquee, I am looking to achieve this desired effect by utilizing jQue ...

Using VueJs to invoke a plugin from a .js file

I'm seeking a deeper understanding of working with vueJS. My current setup In my Login.vue component, there is a function logUser() from UserActions.js which in turn calls the postRequest() function from AxiosFacade.js Additionally, I use a plugin ...

The product image does not display any other images

Hey, I'm experiencing an issue and need help replicating the photo changing effect on this website: I've managed to do everything right except for the photo changing feature (1 / 2 / 3 / 4)!! Here's what I have so far: Can anyone assist m ...