Capture the content from a paragraph element and save it into a variable

Is there a way in VueJS to extract the text from a p tag and save it into a variable?

Currently, the text is just displayed inside the p tag, but I want to store it in a variable for future use.

Here is the HTML code I am working with:

<b-form-input v-model="search" placeholder="Search by disease"></b-form-input>

<select v-model="selected">
  <option v-for="result in filteredPeople(search)" :key="result.LONG_D" :value="{ id: result.LONG_D, text: result.ICD_C }">{{ result.LONG_D }}</option>
</select>
<p>
  Value: {{selected.id}}
</p>
<b-button class="btn" variant="success" v-on:click="runAPI(search)">Search</b-button>

This is my JavaScript code:

export default {
  data() {
    return {
      results: {},
      search: "",
      msg: null,
      selected: ""
    };
  },
  methods: {
    runAPI: function(disease) {
      axios
        .get("http://localhost:9000/api/disease/" + disease)
        .then(response => (this.results = response.data))
        .catch(error => console.log(error));
      console.log(this.results);
    },


    filteredPeople() {
      if (this.searchQuery) {
        return this.results.filter(item => {
          return item.LONG_D.startsWith(this.searchQuery);
        });
      } else {
        return this.results;
      }
    }
  }

Answer №1

To retrieve the value, consider incorporating a function within the tag that can take the value and store it in a variable. This way, the display remains unchanged while still retaining access to the value.

 {{getSelectedId(selected.id)}}

Within {{}}, you have JavaScript capabilities, allowing for functions and conditional logic (although it is advisable to limit complex logic within templates).

Answer №2

If you want to achieve this, you can follow these steps: JS CODE

 export default {
  data() {
    return {
      results: {},
      search: "",
      msg: null,
      selected: ""
    };
  },
 methods: {
runAPI: function(disease) {
  axios
    .get("http://localhost:9000/api/disease/" + disease)
    .then(response => (this.results = this.filteredPeople()))
    .catch(error => console.log(error));
  console.log(this.results);
},


filteredPeople() {
  if (this.searchQuery) {
    return this.results.filter(item => {
      return item.LONG_D.startsWith(this.searchQuery);
    });
  } else {
    return this.results;
  }

HTML CODE

<select v-model="selected">
   <option
    v-for="result in results"
    :key="result.LONG_D"
    :value="{{ id: result.LONG_D, text: result.ICD_C }}">{{ result.LONG_D }}</option>
</select>

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

Is there a way to access a computed property within methods?

Currently, I am utilizing this particular package to implement infinite scrolling in Vue. In order to continuously add new elements during each scroll, I fetch JSON data from my API server and store it in a data object. Subsequently, I divide the array in ...

Dealing with MySQL reconnections in a Node.js REST application

Looking for assistance with my Node.js REST API connected to MySQL. I have encountered issues with the connection closing or timing out. Can someone help me troubleshoot my code: Server.js var express = require("express"); var mysql = require("mysql"); ...

Updating HTML Pages with Dynamic Content

Dealing with a massive project consisting of 50,000 pages (20,000 aspx forms, 10,000 asp forms, and 10,000 html pages) can be overwhelming. With only 2 days to complete the task of adding content after the body tag on all pages, I am seeking advice on ho ...

Issues with Vue router lazy loading causing the failure to generate individual chunk files

I've been attempting to incorporate lazy loading into my routes, but I'm encountering some difficulties. Here's a snippet of how my index.js files in the router folder are set up: import Vue from "vue"; import VueRouter from "vue-router"; i ...

The length of the LinearProgress bar does not match the length of the navbar

Utilizing the LinearProgress component from Material UI, I created a customized ColoredLinearProgress to alter its color: import React, { Component } from 'react'; import { withStyles } from '@material-ui/core/styles'; import { LinearP ...

How to display an image in a pop-up with a title

I am currently using the Bootstrap framework and I am trying to create a popup image with a title, but it only shows the image. I am not sure how to add code in JavaScript to display the title as well. Can someone please assist me? Here is my code: Javas ...

What could be the reason why 'Col' is not functioning properly within React bootstrap?

I am currently implementing react bootstrap with Container, Row, and Col components. However, my code isn't functioning as expected - instead of displaying columns, they are appearing in a row-like fashion. Here is the code snippet that I am referrin ...

The value of an AngularJS model object cannot be altered with a dynamic key

app.controller('indexController', ['$scope', '$location', 'authService', function ($scope, $location, authService) { var vm = this; vm.$onInit = function () { vm.active = { "home": true, ...

Determine the Normalized Mouse Motion Direction Across a Collection Using Three.js

JS Fiddle: http://jsfiddle.net/Nfw9M/1/ I am currently delving into the world of matrix operations and need assistance with a particular problem related to mouse movement on a 3D object. Inside my THREE.Object3D, there are three cube meshes that can be ro ...

Support for SBE protocol within the grpc/javascript framework

Our plan is to utilize grpc for communication between web UI and server, as well as implement SBE as our communication protocol. I have two questions regarding this: Is it possible to integrate the SBE protocol with grpc instead of protobuf? Are there res ...

Navigating through Nuxt.js with random trailing slashes

I've encountered a bit of a snag with a project I'm working on in Nuxt.js. I've set up three pages: register.vue, login.vue, and index.vue. I attempted to use middleware functions to handle redirects between views based on whether a user is ...

Is there a way to automatically add a div to the window as the user scrolls and then hide the div when they scroll back to the

Seeking assistance with creating a function that will add a 'sticky' class to the menu when the user scrolls down to the middle, and then append a div when the 'sticky' class is present. Currently facing issues where the div keeps appen ...

Attach a child element to the bottom of its parent div when the parent div reaches the bottom

I'm looking to make a child div stick to the bottom when the parent div reaches the bottom of the browser window. Note: This behavior should only occur when the parent div is pushed down, not when the page is scrolled down. For instance, in my demon ...

Issues with creating a Dynamic Dependent Select Box using jQuery and PHP

Currently, I am working on a project for my university. The task at hand involves creating four select boxes: Country, State, City, and Course, where the options of three are dependent on the choice made in another. The user's selection will impact th ...

Exploring the Depths of MongoDB Arrays

Below is the structure of my MongoDB data: { "_id": "QEvgJKERy5xGNLv7J", "title": "test 2", "owner": "HQNGYZvrrdQRwLNvT", "markdown": "sdfasdfdasf adsfadsfasdf", "state": "Draft", "category": [ "Bios & Memoirs", "Classics" ], " ...

Displaying Array Information in JavaScript

After spending a significant amount of time searching online, I have not been able to find a working solution to achieve what I need. Essentially, I am making an AJAX request that executes a database query and then outputs the results using echo json_enco ...

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...

Is there a way to identify when no rows contain specific values in PostgreSQL or node.js and return false?

Here is an example of a table: P Q t f f t f f In SQL, is there a way to return false when querying for t t, but true when querying for t f, f t, or f f? Should this be handled with node.js by first doing a select and then using if-else statements based ...

The ngModel functionality struggles to accurately detect changes within arrays

The component model: private SomeArray = [{ key: "Initial" }]; User has the ability to dynamically add or remove items: addField() { this.SomeArray.push({ key: Math.random().toString() }); } removeField(index: number) { this.SomeArray.splice(ind ...

Sending data from a Javascript variable to Java in JSP

I need help with passing a Javascript value to a Java function in JSP. What is the best way to achieve this? The ID I want to pass comes from a combobox in JSP through Javascript. My goal is to extract the ID from the combobox and then pass it as a paramet ...