Inspecting a substring of an element dynamically added in VueJs

When I click a button in my form, it adds a new line. The challenge is making sure that each new line evaluates independently and correctly. In this case, the task involves checking the first 2 digits of a barcode against a dataset to determine a match or return "nothing found". At the moment, the evaluation is not working as expected - it always displays "No Agency found" and applies this to all fields because they share the same v-model on a new line add. How can I modify this so that each field is evaluated correctly and independently?

Below are the relevant sections from my template and script:

<div id="q-app" class="q-pa-lg">
 <!-- Code snippet here -->
</div>


export default {
  data() {
    return {
        // Data properties listed here
    };
  },
  methods: {
      // Methods defined here
  },
  mounted() {
      // Code for mounting the application
  } 
}

For a more detailed look at the code, check out the codepen.

Answer №1

Here are a few things to consider in this code:

To avoid confusion, try not to name loop variables the same as top-level data elements. Instead of

<div v-for="(barcodefield, index) in barcodefields" :key="index">
, use
<div v-for="(item, index) in barcodefields" :key="index">
. Then make sure to update all instances of barcodefield.start and barcodfield.end to item.start and item.end.

Furthermore, ensure that each item has its own unique agencyName instead of all items sharing the same value.

Modify the showAgencyName method like so:

showAgencyName(item) {
    var str = item.end;
    var res = str.substring(0, 2);
    if (this.barcodeprefixes[res] == undefined) {
        item.agencyName = "Agency not found";
    } else {
        item.agencyName = this.barcodeprefixes[res];
    }
},

Then, call it using @blur="showAgencyName(item)"

Lastly, utilize it in the HTML like this:

<div v-if="item.agencyName" style="min-height: 40px">
    {{ item.agencyName }}
</div>

(You can also remove the top-level barcodefield from the data object since it is no longer needed.)

Check out the updated version on: https://jsfiddle.net/ebbishop/7r1pqx9f/

Answer №2

  • To start off, recommend renaming the variable used in the for loop from "barcodefield" to avoid conflicts with existing data structures.
  • Next, consider utilizing a function like {{ getAgencyName(b) }} instead of directly using {{ agencyName }} to ensure unique agency names for each line.

Answer №3

There seems to be a couple of issues with this code snippet. First, there appears to be a typo in the barcodefield data object where "star" is used instead of "start."

Additionally, within the showAgency method, references to the non-existent this.barcodefield properties are made. One solution could be passing the index of the barcodefield to the showAgencyName method and using it to access the desired barcodefield from the barcodefields array.

In the HTML section:

<q-input outlined square dense maxlength="24"
v-model.trim="barcodefield.end" @blur="showAgencyName(index)" ref="bcentry"></q-input>

The showAgencyName method should look like this:

showAgencyName(index) {
    const barcodefield = this.barcodefields[index]
    var str = barcodefield.end;
    var res = str.substring(0, 2);

    if (this.barcodeprefixes[res] == undefined) {
        this.agencyName = "Agency not found";
    } else {
        this.agencyName = this.barcodeprefixes[res];
    }
}

UPDATE: Upon closer inspection, another issue has been identified. The agencyName variable gets overwritten each time a new barcodefield is added since it functions as a global value. I have updated the Codepen with a simple solution - now the name of the agency is returned from the showAgencyName method and displayed on the interface. There are various other potential solutions for this problem (such as adding the name to the barcodefields object in the array).

For a working example, check out this Codepen

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

Unexpected JavaScript Bug (with jQuery)

I have an interesting code snippet that captures button clicks and then hides the existing content, revealing the content of the clicked item instead. This code is part of my init.js file along with other functionalities: $(function() { $('#conta ...

Showing JSON data as a table in an HTML format

After receiving the JSON String from the server as a response, which can be viewed here, I've implemented the following Jquery Code: function loadCategories() { $.ajax({ type: "POST", url: "/Services/ControllerService. ...

The Javascript style.opacity function eliminates the leading zero from the input string

In my application, users have the ability to change the color of the background but not the pattern. They can adjust the background behind the pattern and the opacity of the pattern. Users are prompted to input a percentage, which is actually a number betw ...

Error encountered while scrolling with a fixed position

I am currently in the process of developing a carousel slider that resembles what we see on Android devices. The main challenge I am facing at this early stage is applying the CSS property position: fixed; only horizontally, as vertical scrolling will be n ...

What is the Most Effective Way to Generate Sequential Output in PHP?

What is the most effective method for creating a sequential output in a PHP installation script? Let's say I have a webpage and want to show progress updates within a DIV using PHP. For example, the page.html file could include: <div id="output"& ...

Transfer the imageURI to a different HTML page

My mobile app, created using PhoneGap, allows users to select an image from their album. I want to pass that selected image and display it on another HTML page. Does anyone have any suggestions on how to achieve this? Below is the code snippet: selectImag ...

Changing text on a button with JavaScript toggle functionality: A step-by-step guide

I am looking to implement a feature where I can hide and show overflow content in a div. When I click on the expand button, it expands the content. However, I want this button to toggle and change text as well. Thank you! function descriptionHeightMo ...

What is the best way to combine two responses and then convert them into a promise?

When making two calls, the firstCallData prints data fine. However, when I use + to merge the responses, it returns me the following Response. What is a better approach to achieve this task? main.ts let data = await this.processResponse(__data.Detail ...

Creating dynamic styles with Material-UI's useStyles

Attempting to implement the same logic using material-ui's useStyle feature <div className={'container ' + (state.unlocked ? 'containerUnlocked' : '')}> I thought it might look like this: <div className={`${clas ...

Creating a binary tree in vanilla JavaScript and styling it with HTML and CSS

I'm facing a challenge with my homework. I am required to convert my JavaScript binary tree into HTML and CSS, strictly using vanilla JavaScript without any HTML code. I have the tree structure and a recursive function that adds all the tree elements ...

v-select/Vue: Can I input a value that is not in the dropdown list?

I'm looking for a solution to include a new value in v-select that is not already in the list. I want the newly entered value to be selected as an option. Below is my existing code: <v-select ref="systemSelect" v-model="reservation.system" ...

Execute multiple events using jQuery's .trigger() method

As I develop a jQuery plugin, I am utilizing the .on and .trigger functions for my pub/sub system. One challenge I am facing is triggering multiple events in different scenarios with ease. My question is whether it is possible to trigger multiple events a ...

Express.js fails to redirect to the sign-in page after successfully retrieving the username from the MySQL database

I have encountered an issue while trying to retrieve the username from a MySQL database. The code I am using successfully retrieves the username, but when an error occurs, instead of redirecting to /signin, it redirects to /admin. Adding res.redirect(&ap ...

Substitute a particular element within a text

I'm currently working on an Angular 9 application where I'm implementing search filters for the Shopify Graphql API. As part of this process, I am constructing a query which looks like: first: 1, query: "tag:'featured-1'", af ...

The Philosophy Behind Structuring Node.js Modules

There appears to be a common understanding regarding the directory structure in node.js, but I have not come across any official documentation on this topic. Based on my exploration of open source projects, it seems that most projects typically include a ...

how to open a new tab using JavaScript with Selenium

My code is supposed to open a new window that goes from the login window to the main menu, module, reports, and finally the report name. The report name should be opened in the next tab. Issue: The report name is not opening in a new tab; it's openin ...

Ensure the buttons within v-card-actions are responsive to different screen sizes

I am facing an issue with a v-card that contains three buttons (v-btn) within v-card-actions. Each button has long text on it, which is causing alignment problems on small screens. The buttons are not responsive and are still aligned horizontally from left ...

The route path consists of data that will be retrieved before entering the route

I am facing an issue with my router configuration. I have a dynamic Route that requires the last part of its path to be set after fetching data from a store call in beforeRouteEnter. beforeRouteEnter (to, from, next) { if(to.params.categoryId) { next(vm ...

issues encountered when trying to integrate bootstrap.js in Django framework

My website is built using the Django templating engine with Bootstrap for design and basic JavaScript. While the CSS components from Bootstrap are working fine, I'm having trouble getting the JavaScript to work: {% load staticfiles %} <!d ...

What is the most effective method for serializing SVG data from the client's Document Object Model (DOM

As I delve into the world of creating interactive SVG/AJAX interfaces, I find myself faced with a challenge. Users are constantly manipulating elements on-the-fly and I want to give them the option to export their current view as a PNG image or an SVG docu ...