What is the best way to retrieve the value of a text box in VUEjs using its unique identifier?

In my form, there are a total of two text boxes with predefined values. However, I am looking for a way to retrieve the value of one specific textbox based on the entered ID number.

For example, if I input "1," I expect to see the value of text box 1 only.

https://i.sstatic.net/3K1xV.jpg

Currently, my implementation fetches data from both text boxes, which is not the desired outcome.

See below for the template:

<input v-model="textdata1" id="1" type="text" placeholder="i am id1, show my value">

<input v-model="textdata2" id="2" type="text" placeholder="i am id2, show my value">

<input v-model="searchid" type="text" placeholder="Specify the ID (1 or 2) you want to retrieve data for">

<button @click="getvalue">RECEIVE</button>

<div>The value of the specified ID will be shown here: {{id1data}}</div>

Implemented using VUEJS:

<script>
import { defineComponent, ref } from 'vue'

export default defineComponent({
  setup() {
    const id1data = ref("");
    const id2data = ref("");

    function getvalue(){
        this.id1data = this.textdata1;
        this.id2data = this.textdata2;
    }

    return {
      id1data,
      id2data,
      getvalue,
    }
  }
})
</script>

Answer №1

If you are adamant about utilizing IDs, here is a method to achieve that:

<script>
import { defineComponent, ref } from "vue";

export default defineComponent({
  setup() {
    const value = ref("");

    const searchid = ref("");
    const searchidinput = ref("");

    function retrieveValue() {
      this.searchid = this.searchidinput
      const element = document.getElementById(this.searchid);
      if (element) {
        this.value = element.value
      }
    }

    return {
      value,
      searchid,
      searchidinput,
      retrieveValue,
    };
  },
});
</script>

<template>
  <input id="1" type="text" placeholder="i am id1, show my value" />

  <input id="2" type="text" placeholder="i am id2, show my value" />

  <input v-model="searchidinput" type="text" placeholder="which ids data you want, 1 or 2 " />

  <button @click="retrieveValue">GET VALUE</button>

  <div>show value of id {{ searchid ? searchid : "<none>" }} here: 
{{ value ? value : "none selected"}}
    
  </div>
</template>

<style scoped>
a {
  color: #42b983;
}
</style>

Answer №2

If you're looking for a solution, here's an approach that could help. Consider creating a set of data pairs for each input.

<script>
import { defineComponent, ref } from "vue";

export default defineComponent({
  setup() {
    const textdata1 = ref("");
    const id1data = ref("");

    const textdata2 = ref("");
    const id2data = ref("");

    const searchid = ref("");
    const searchidinput = ref("");

    function getvalue() {
      this.searchid = this.searchidinput;
      switch (this.searchid) {
        case "1":
          this.id1data = this.textdata1;
          break;
        case "2":
          this.id2data = this.textdata2;
          break;
      }
    }

    return {
      textdata1,
      id1data,
      textdata2,
      id2data,
      searchid,
      searchidinput,
      getvalue,
    };
  },
});
</script>

<template>
  <input v-model="textdata1" id="1" type="text" placeholder="i am id1, show my value" />

  <input v-model="textdata2" id="2" type="text" placeholder="i am id2, show my value" />

  <input v-model="searchidinput" type="text" placeholder="which ids data you want, 1 or 2 " />

  <button @click="getvalue">RECEIVE</button>

  <div>show value of id {{ searchid ? searchid : "<none>" }} here: 
{{ searchid === "1" ? id1data : searchid === "2" ? id2data : "none selected"}}
    
  </div>
</template>

<style scoped>
a {
  color: #42b983;
}
</style>

An alternative option is to utilize reactive() for better conciseness and organization purposes.

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

Best practice for structuring an object with multiple lengthy string elements in the GCP Datastore Node Library

My JavaScript object is structured like this: const data = { title: "short string", descriptions: [ "Really long string...", "Really long string..." ] } I need to exclude the long strings from the indexes, but I ...

The A-frame advances in the direction of the camera's view

I need help creating a component in A-frame that can move the player or camera based on the direction it is facing. The movement should be restricted to the x/y plane and not affect the y axis. Currently, my DOM setup looks like this: <a-entity> ...

Ensure NodeJS/JSDom waits for complete rendering before performing scraping operations

I am currently facing an issue with scraping data from a website that requires login credentials. When I try to do this using JSDom/NodeJS, the results are inconsistent compared to using a web browser like Firefox. Specifically, I am unable to locate the l ...

Issue with ReactJS and Material UI: FlexGrow functionality malfunctioning

I'm currently grappling with the implementation of FlexBox, particularly in understanding how to effectively utilize flexGrow. Despite my efforts, I haven't been able to achieve the desired result as the background appears to only wrap around the ...

Steps to assign a value to an input element using the state in a React application

Hey there, I hope everything is going well for you! I have a question regarding setting the value of an input field based on the state received from props. I've tried to populate the input with data from the "profile" state using placeholders, but it ...

Experiencing a problem with XAMPP? Changes made to the code are not reflected after saving

Recently, I've encountered a strange issue with my XAMPP test server while working on a game project. Everything was running smoothly until I noticed that when I make changes to certain files in Notepad++ and save them, the updates are not being refle ...

Tips for effectively passing a $scope object between various controllers

I am encountering an issue with sharing a $scope object between two controllers. Within the 'IssueBookCtrl' controller, I update the 'books' object element value like this: $scope.books[i].issued = true; After that, I use the $emit s ...

Guide to accessing component methods within slots using the Vue 3 Composition API

I have child components within a slot in a parent component and I am trying to call methods on them. Here are the steps I followed: Use useSlots to retrieve the child components as objects Expose the method in the child component using defineExpose Call t ...

Implementing a language switch feature with Vue, Vuex, and Vue-i18n

Why doesn't the page update in a new language when the mutation is changed? In my main.js file, I have implemented vue-i18n with Vue: import Vue from 'vue' import VueRouter from 'vue-router' import VueResource from 'vue-reso ...

Creating a production-ready installation of Tailwind CSS with Vue 3

Although I primarily develop in Python, I found myself struggling with npm after trying to integrate Tailwindcss with 'Vue 3'. Following the installation steps outlined on the Tailwind+Vue 3 website, I ran into some issues. npm init @vitejs/app m ...

What are the best practices for managing POST data in Express.js?

Lately, I've been consistently encountering 500 errors from Express.js which seem to stem from a failure to retrieve a crucial string key required by the request. On the client side, numerous requests are being made to the same endpoint (/restore), a ...

Toggle visibility of various items in a to-do list, displaying only one item at a time with the use of JavaScript

I am currently working on a web project using the Laravel framework. I am struggling with implementing a feature where only the title of each to-do item is displayed, and when clicked, it should reveal the corresponding content. However, I have encountered ...

React Table Pagination Bug with Material UI Library

I am currently using Material UI and referencing the table sample provided at https://material-ui.com/demos/tables/. However, when attempting to implement the Custom Table Pagination Action according to the sample, I encountered an error. The error "inher ...

Is it possible to use nodemailer locally with NodeJS? The issue is that the greeting emails are not being received

Every time I attempt to send an email using nodemailer within my local network, I encounter the following error: *Greeting never received at SMTPConnection._formatError (C:\Users\PI_TEAM\Desktop\node_modules\nodemailer\lib ...

show information from json onto an html page with the help of jquery

I'm looking to showcase buttons from a JSON file within a simple block. Here's the JSON data for movies: { "movies": [ { "title": "Mena", "movieid": "1", ...

Passing all selected items from a list to the controller

I am currently facing an issue with my two multi-select lists. One list contains a full list of names while the second one holds the names that have been selected from the first list. The names are stored in a Vue array which populates the names into the s ...

Creating a custom ID for a Firebase POST request

Is it possible to assign a custom ID in Firebase when using the POST method? For example: { "users": { "user_one": { "username": "jdoe", "password": "123" } } } I'm currently working on a Vue.js project and I want to save ...

Setting default date and time for Bootstrap datetimepicker only in the expanded calendar view

Here is the setup: $(function () { $('#datetimepicker').datetimepicker({ defaultDate: moment(), sideBySide: true }); }); This configuration allows setting a default date & time when no value is provided for the f ...

IE8 encountering issues with Jquery ajax() request

My current issue involves submitting data using ajax from forms with a class of ajax. This functionality works flawlessly in Firefox, Safari, and Chrome, but is unsuccessful in Internet Explorer. ajax: function() { $('form.ajax').live(&apo ...

Asynchronous callback in mongoose with an undefined value

I am utilizing 'mongoose' and 'async'. While my search functionality is operational, I encounter an issue where my data does not get passed in the final callback. The variable always ends up being undefined. Despite referencing the mong ...