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

Can Vue 3 be utilized with both the composition API and vue class components?

For the past 8 months, our project has been developed using Vue 3 and the class components. However, it appears that the class components are no longer being maintained. Therefore, we have decided to gradually transition to the composition API, specificall ...

What is the best way to access a promise's value in global scope within a reactjs application?

Currently tackling user authentication using web tokens in react. My approach involves utilizing the fetch() method to send a POST request to my backend, facilitating CORS. The issue arises when attempting to employ the setToken() hook within the .then() b ...

Retrieving the custom attribute value from the chosen option and storing it in a JavaScript variable

I am currently working on a project that involves a country select input, with custom attributes included in the options. My goal is to retrieve the value of the "name" attribute using JavaScript and then append it to a link for further processing. Howev ...

Cautionary alert while displaying a data binding from a controller in AngularJS

Adding a numerical value to the controller: this.myValue = Number(elem.toFixed(2)); Then placing it inside an input form: <input class="my-input" type="number" value={{$ctrl.myValue}} ... > Although the value ...

Struggling to grasp the concept of async/await and promises

I'm fairly new to working with node.js and JavaScript in general. I've been trying to understand promises and async/await concepts, specifically in the context of requesting images from a remote URL asynchronously and converting them to base64 fo ...

Tips for inserting a logo in the center of a QR code using Node.js

I'm currently working on designing a logo and attempting to incorporate it into the center of a QR code. While I've been successful in generating the QR code, I'm facing challenges in getting the logo to appear in the middle. I've tried ...

Unable to show an image within the <div> element when hovering the mouse

Is it necessary to use the background style image in order to display an image on mouseover of a name? I have implemented a controller and would like the image to be replaced by text within a div tag. Below is my HTML code: <!DOCTYPE html> <html& ...

Using AJAX in a Django application within a RESTful ecosystem

I am new to the world of restful programming and have a Django website. My goal is to dynamically load a part of the website. Currently, my workflow is as follows: When I call a URL (such as localhost:8080/index), it routes to the Django view, which retr ...

Ways to reduce the size of images within a bootstrap carousel

I'm currently working on creating a carousel that will serve as a background image cover for my website, similar to the revolutionary slider in WordPress but without using a plugin. I am developing it specifically for my static website. The challenge ...

Troubleshooting JQuery AJAX HTML Problems in Google Chrome and Firefox

I'm facing an issue with my code and I'm not sure what to do. It works perfectly on Internet Explorer, but when I try to open it on Chrome or Mozilla, the links in my menu don't work! I click on them but nothing happens. Can someone please h ...

What purpose does process.env.NODE_ENV serve within my Vue.js custom component?

Struggling to develop a custom HTML element using vuejs and vite. Each time I build the element, process.env.NODE_ENV is inserted into the js, causing issues when trying to use the component outside of vuejs. My aim is to create an element that can be util ...

I'm having trouble with installing nx as it keeps showing the error message 'Platform Dependency for NX is Missing.'

I encountered an issue when running npm install: $ npm i npm WARN deprecated @babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b5b475e4c4245065b59445b44584a470648474a5858065b59445b4e595f424e586b1c051a13051d">[email  ...

Can you explain the step-by-step process of how an await/async program runs in TypeScript/JavaScript or Python?

As a C++ developer specializing in multithreading, I've been diving into the intricacies of async/await. It's been a challenge for me as these concepts differ from how C++ programs are typically executed. I grasp the concept of Promise objects, ...

Using Vuex in the router: A comprehensive guide

I am having trouble accessing data from the store in the router. I have attempted three different methods, but none of them seem to be working correctly. Here are the methods I tried: // ReferenceError: store is not defined console.log(store.state); // ...

A guide on smoothly navigating to the desired row in a gridview using Asp.net

Currently, I am developing a project using ASP.net and C# technology. In my application, I integrated a GridView that contains multiple rows. Within the grid, there is a text box and a search button available. The columns displayed in the grid are Id and ...

Looking for visible elements in WebDriverIO?

Currently, I am developing a test suite using WebDriverIO for a website with multiple duplicate elements that are selectively displayed based on user interaction... For example, the site may contain five buttons that each open a tooltip. These tooltips ar ...

Tips for preventing the colors of all buttons from changing when only one is clicked in JavaScript

const tasks = `[{ "taskName": "Task 1", "image": "./images/task1.jpg", "description": "Task 1 description", "importance": 0 }, { "taskName": "Task 2", "image": "./images/task2.jpg", "description": "Task 2 description", ...

Encountered a discrepancy with npm dependencies during the update or installation process on a legacy project

I am encountering issues while attempting to run an older project. Every time I try to npm install or start the project, it throws various dependency errors, particularly related to the outdated npm version. My current node version is 16.x, whereas the pro ...

Implementing a dynamic listbox feature in JSP

I have a setup with two listboxes on my JSP page. The first listbox is initially populated with data from the database. When a user selects an item in the first listbox, I want the second listbox to be filled with corresponding database data using Ajax. Si ...

Is there a way to horizontally center Material UI Switch and its icon props?

I'm using Material-UI to implement a Switch component on my project. This particular component allows for the addition of icons, however, I've encountered an issue with alignment when including them. Is there a way to horizontally center align b ...