Unspecified tag name attribute in Vue that can be accessed in the browser

At the moment, I have encountered an issue with a selector in Vue returning undefined for {{ lens.price }}. However, when I use

a = lens[1].getAttribute('price')
in the browser console, it correctly displays the value as "0".

Why is Vue showing this data as undefined? The property works perfectly fine in the browser for all options returned from the loop.

Should I combine both properties into a single value tag name?

HTML/LIQUID:

<div>
      <label for="lens"></label>
      <select id="lens" name="line_items[lens]" @change="handleChange('lens', $event); secondChange($event);"
        class="mt-3 option-selector text-sm lg:text-base uppercase block appearance-none w-full bg-white text-gray-900 py-3 px-4 pr-8 rounded-sm leading-tight focus:outline-none focus:border-black font-bold">
        <option>Choose a lens</option>
        {% for lens in collections.lenses.products %}
        <option price="{{ lens.price }}" value="{{ lens.variants[0].id }}">{{ lens.title }} |
          {{ lens.price | plus: product.price | money_without_trailing_zeros}}</option>
        {% endfor %}
      </select>
    </div>

BREAKDOWN OF VUE: (NOT COMPLETE CODE)

data: function () {
    return {
        buttonText: false,
        slideOut: false,
        disableAddToCart: true,
        chosenLens: '',
        chosenFilter: '',
        lensPrice: ''
    }

handleChange(type, e) {
        if (type === 'lens') {
            if (e.target.value) {
                this.chosenLens = e.target.value;
            }
            else {
                this.chosenLens = ''
            }
        }
        if (type === 'filter') {
            this.chosenFilter = e.target.value || ''
        }
        this.disableAddToCart = !(this.chosenLens && this.chosenFilter);
    },
    secondChange(e) {
        this.lensPrice = `${e.target.price}`;
    },

I tried using Javascript only: (resulted in undefined)

<div>
    <label for="lens"></label>
    <select id="lens" onchange="myFunction()" name="line_items[lens]" @change="handleChange('lens', $event);"
      class="mt-3 option-selector text-sm lg:text-base uppercase block appearance-none w-full bg-white text-gray-900 py-3 p...
    <option>Choose a lens</option>ө

</script>

Using only attribute name 'value': (working)

    <div>
  <label for="lens"></label>
  
</script>

Answer №1

Starting point:

e.target.value

The object e represents the browser event.

e.target refers to the <select> element.

A <select> element has a property called value which corresponds to the currently selected value, taken from the attribute of the selected <option>.

Upon selection:

  1. User selects an <option>.
  2. The value attribute of the <select> is set to match that of the selected <option>.
  3. A change event is triggered for the <select>.

The value attribute carries significance in HTML unlike other attributes such as price.

This behavior can be observed without Vue as well with the following example:

document.getElementById('lens').addEventListener('change', function (ev) {
  const target = ev.target
  console.log(target.tagName, target.value, target.price)
})
<select id="lens">
  <option value="A" price="1">First</option>
  <option value="B" price="2">Second</option>
</select>

Although Vue has special handling for non-string values bound to <option> elements using v-model, the issue you're encountering is not specific to Vue.

Answer №2

Although this might not be the most elegant solution, I managed to implement a quick fix using the split() function for now. The issue arises from Vue expecting data to be retrieved from "value" and not any other attribute name.

<option value="{{ filter.variants[0].id }}-{{ filter.price }}"><span>{{ filter.title }} +
  </span><span>{{ filter.price | money_without_trailing_zeros }}</span></option>

priceMethod(type, e) {
        if(type === 'lens')
        if (e.target.value) {
            let a = e.target.value
            a = a.split("-")[1]
            a = a.replace('00', '')
            console.log(a)
            a = parseInt(a)
            this.lensPrice = a;
        } 
        if (type === 'filter') {
            let b = e.target.value
                b = b.split("-")[1]
                b = b.replace('00', '')
                b = parseInt(b)
                console.log(b)
            this.filterPrice = b || ''
        }

Answer №3

Finally, I achieved success using the same method as described below.

<select id="vehicle"  @change="removeItem()">
      <option type="button" data-price="$189">
          $189
      </option>
      <option type="button" data-price="$459">
           $459
      </option>
    </select>

new Vue({
  el: '#vehicle',
  methods:{
    removeItem: function(){
        var carSelection = document.getElementById("vehicle");
        var selectedCar = carSelection.options[carSelection.selectedIndex].dataset.price;
        alert(selectedCar)
    }
  },
})

The result is an alert showing the data attribute of $189 when changed or $459 when changed. Additionally, @click functionality also works.

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

Error encountered while attempting to install material-ui v3.0.3 due to an unexpected termination of the JSON input

I'm currently in the process of installing the most recent stable version of material-ui(v3.03) by running: npm install @material-ui/core. However, I encountered an issue with npm ERR! Unexpected end of JSON input while parsing near '...-/brcast- ...

Using two variables for iteration in Vue.js v-for loop

Can you create a v-for loop with two variables? I attempted the following, but it did not function as expected <ul id="example-1"> <li v-for="apple in apples" v-for="banana in bananas"> {{ apple .message }} {{ banana .message }} & ...

The knockout click event isn't functioning properly for a table generated by ko.computed

My goal is to connect a table to a drop-down menu. Here are the key points of what I'm trying to achieve: The drop-down should list MENUs. Each MENU can have multiple MODULES associated with it, which will be displayed in the table based on the ...

The offcanvas close button fails to function if initialized through JavaScript

I have integrated offcanvas into the page layout. By default, it remains hidden but I want it to be visible at all times on large screens. On smaller screens, there should be a button to dismiss it, as well as another button in the menu panel to show the o ...

Are there any AJAX tools or packages in Node.js Express for connecting (posting/getting) with other servers and retrieving data?

Can someone please guide me on how to utilize ajax in node.js to send and receive JSON data from another server? Is there a package available that allows for this functionality, similar to jQuery's $.ajax, $.post, or $.get methods? ...

Configure markers on Google Maps

I've been attempting to integrate my markers into Google Maps, but I'm stuck on how to use the following: map.fitBounds(latlngbounds); Any ideas on how I can implement this easily? Below is the code I have so far: <script type="text/javas ...

Incorporate a course within the conditional statement

Currently, I'm working on the development of an input site and one of my goals is to highlight empty fields. My plan is to check if a field is empty using an if statement and then apply a specific class that will serve this purpose. This is the JavaS ...

Issue with Material-UI AppBar buttons repositioning to center of screen upon page refresh

One of the components in my project is a Material-UI AppBar, which consists of various elements such as icons and buttons. Here is the code snippet for this component: import React from 'react' import AppBar from 'material-ui/AppBar' i ...

The Material-ui Drawer does not function properly when used with an external CSS file

For my project, I'm working on a Sidebar design that is inspired by the Mini Variant drawer demo available at this link. However, the project requirements mandate that all CSS styling should be done in a separate CSS file rather than directly within t ...

Exploring the compatibility of Husky with Typicode using Yarn

Currently, I have implemented the use of husky to configure git hooks for prettier. However, I am facing a persistent issue whenever I attempt to commit or push: > husky - Can't find npm in PATH. Skipping precommit script in package.json My curre ...

Ways to loop through a collection of indexed elements

I am working with an array of indexed objects and my goal is to iterate through it in order to transform it into a new flattened array. Here is the initial array of objects: "attentionSchedules": [ { "room": "1", ...

Adjust image size based on the size of the screen

I am facing an issue with two images that are created for a 1024 x 768 resolution but I need to use them in a higher resolution. The challenge is to align these two images so that the circle from the first image falls between the second image. Although I ...

Setting filters programmatically in Mui X Data Grid

I am currently working with the MUI Data Grid (pro version) and I am looking to implement checkboxes in the sidebar to filter different columns. Consider three columns: * Column Letters: ['a', 'b', 'c', 'd', etc.] * ...

exciting, showcasing a dependency map using svg within an html5 environment

I am working on creating a polygon background for my menu, which needs to be responsive in design. Here is an example of what I am trying to achieve: example image. Should I use JavaScript to listen for size changes and adjust the points for the polygon e ...

Hindering advancement: Bootstrap Form Wizard causing roadblocks

I am currently facing an issue with my form wizard setup. I want to prevent the user from advancing to the next step when the success key in my json is set to false. It seems like the project is utilizing the bootstrap wizard plugin. You can find more in ...

What is the best approach for managing validations on a field-by-field basis within a Formik FieldArray?

Scenario: When there are 3 participants, each participant will receive a set of questions. However, the display of each question is dependent on a list of "applied tickets" associated with the question. TLDR; I need to understand: if it's possible ...

Encountering a hindrance with NPM proxy while attempting to globally install Vue CLI

I have encountered an issue while trying to install Vue Cli globally. The installation process is not completing and I am receiving errors related to proxy settings. I tried to manually add values to the .npmrc file as shown below, but it did not resolve t ...

Attempting to loop through a JSON data structure in a React component

Trying to add a toggle checkbox for each JSON value present. Here is an example of the json object pertaining to element { "sourceIP": { "Primary": ["237.100.100.3", "238.0.4.8"], "Secondary": ["237.0.1.178", "237.1.1.91"] }, " ...

Preserve the ajax controls while uploading files

I encountered a minor issue with file uploading. When I click the upload button, a window (ajax powered) pops up for selecting a file. However, as soon as the file is uploaded to the browser, the page reloads and the window closes, leaving me without the ...

Scrolling using JavaScript's 'smooth scrolling' feature is currently disabled

Background of the Issue: I am in the process of creating a one-page website using Twitter Bootstrap 3 within an ASP.NET MVC project. The Challenge: My current challenge involves implementing 'smooth scrolling' functionality that scrolls to the ...