Unlocking elements in Vue.js through functions

Looking to dynamically add a class to the label element when focusing on an input element below it. The current HTML and JS code I'm using is as follows:

HTML:

<label for="formProductId" ref="productIdLabel" class="form-element-title">Product ID</label>
<input id="formProductId" @blur="toggleFocus('productIdLabel', false)" @focus="toggleFocus('productIdLabel', true)" v-model="filterValues.productId" :name="filterOptions.productId === true ? 'productId' : false" type="text">

JS:

toggleFocus(ref: string, enable: boolean) {
    if (enable) {
        (this.$refs[ref] as HTMLElement).classList.add("js-focused");
    } else {
        (this.$refs[ref] as HTMLElement).classList.remove("js-focused");
    }
}

Wanting to enhance this functionality by removing the ref attribute and toggling the js-focused class directly from the selected element. Any ideas on how to select the closest label element and modify its class?

Answer №1

A more efficient approach involves utilizing dynamic classes. Take a look at this example:

new Vue({
  el: '#app',
  data: {
    productIdLabel: false
  }
})
.js-focused {
  background-color: lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <label for="formProductId" class="form-element-title" :class="{'js-focused': productIdLabel == true}">Product ID</label>
  <input id="formProductId" @blur="productIdLabel = false" @focus="productIdLabel = true" type="text">
</div>

Implement this with components and multiple form inputs:

Vue.component("form-label", {
  template: `<div>
  <label :for="info.id" class="form-element-title" :class="{'js-focused': isFocused == true}">{{info.label}}</label>
   <input :id="info.id" @blur="isFocused = false" @focus="isFocused = true" type="text">
</div>`,
props: ["info"],
data: function(){
return {
isFocused: false
}
}
})
new Vue({
  el: '#app',
  data: {
    form: [{
      label: "Product Id",
      id: "formProductId"
    }, {
      label: "Another Element",
      id: "anoterId"
    }, {
      label: "Third Element",
      id: "thirdId"
    }]
  }
})
.js-focused {
  background-color: lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <form-label v-for='el in form' :info='el'></form-label>
</div>

Answer №2

You can utilize the previousElementSibling property in combination with event.target.

For instance:

new Vue({
  el: '#app',
  methods: {
    toggleLabelColor(event) {
      event.target.previousElementSibling.classList.toggle('input-focused')
    }
  }
})
input {
  display: block;
}

.input-focused {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <label>I turn green when focused.</label>
  <input @focus="toggleLabelColor" @blur="toggleLabelColor">

  <label>I turn green when focused.</label>
  <input @focus="toggleLabelColor" @blur="toggleLabelColor">

  <label>I turn green when focused.</label>
  <input @focus="toggleLabelColor" @blur="toggleLabelColor">
</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

Divs animated with jQuery keep on moving even after the animation has finished

My current project involves animating a single circle that scales, collides with two nearby circles, and then causes those circles to animate to specific positions. While everything works as expected, there is an issue where the two circles involved in the ...

Can you identify the HTML table format and suggest effective web scraping methods?

I have been attempting to retrieve data from the following link, http://www.rchsd.org/doctors/index.htm? strt = 0 & ln = & fn = & sp = & grp = & loc = & lng = & gen = , using R but finding it quite challenging. I have observed that the URL remains constan ...

Looking to incorporate CGST and SGST into the Subtotal using JQuery?

I have come across this particular HTML Code in an Invoice: <tr> <td colspan="3" class="blank"></td> <td colspan="2" class="total-line">Subtotal Rs.</td> <td td class="t ...

What are the steps to ensure that all resources are localized?

I am working on a web application using Nuxt.js and Vuetify addon. It needs to function offline, but I am encountering errors when trying to download css and fonts externally. Here is the issue I am facing: https://i.sstatic.net/y2zML.jpg Is there a way ...

Set up a Bootstrap date picker to populate two input boxes with a start and end date. Additionally, disable the ability for the date value to change

In my project, I have implemented Bootstrap Datepicker to set two input boxes for selecting start and end dates. The rule is that the start date must be after today and the end date must be after the selected start date. To disable specific dates in the da ...

Conquering Challenges Across Multiple Disciplines

Is there a solution to solving the cross domain issues that arise when trying to fetch data from a different web server on the client-side, in violation of the Same Origin policy? ...

"Unleashing the Power of AngularJS: Implementing a Global Error Handler to Display and

When building my website, I have multiple Angular apps that require a global error handler to track and display alerts for errors with codes like 500 and 401. Here is what I have so far: In order to create a global error handler module, I've set up t ...

What is the best way to create a Laravel object for use in JavaScript in a Laravel Blade?

please add description hereI am looking to obtain an object with this particular style var zoz2= { "11-30--0001": "<a href=\"https:\/\/www.dooz.ps\/p\/107229\" >\u0625\u0637\u0644\u0627& ...

Opencart: The Key to Your Website's Success

Quick question - I have a Java snippet that needs to be added to my OpenCart checkout page before the closing </body> tag. However, I cannot locate the </body> tag in the checkout.tpl file of OpenCart. Can anyone guide me on where to find thi ...

Unable to delete a dynamically inserted <select> element by using the removeChild method

As someone who is new to coding web applications, I am currently working on a project that involves adding and deleting dropdowns dynamically. Unfortunately, I have run into an issue where the delete function does not work when the button is pressed. Her ...

MUI: Autocomplete cannot accept the provided value as it is invalid. There are no matching options for the input `""`

https://i.stack.imgur.com/KoQxk.png Whenever I input a value in the autocomplete component, an unresolved warning pops up... Here's how my input setup looks: <Autocomplete id="cboAdresse" sx={{ width: 100 + " ...

Running a Node.js script on an Express.js server using an HTML button

I've got an HTML button: <button id="save" type="button" onclick="save()">Save</button> and in my JavaScript code, I want it to execute something on the server side using node.js Here's what I have in mind: function save() { / ...

Guide to adding a URL link to an image tag in Vuetify and Nuxt.js

Hello! I am currently navigating the world of Nuxt.js and Vuetify, and I have a question about adding URL links to image tags. Essentially, I want users to be able to click on an image and be directed to another page via a designated link. About My Page L ...

Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element: function draw(json) { if (json["leaf_text"]) { stroke(100) el ...

Pass information from Vue JS v-for to a button when it is clicked

Just started learning Vue JS and encountered a small issue I'm currently looping through an array with a button inside the div I'm iterating over The goal is to grab the data of the selected item after clicking on the button For example, suppo ...

Sending JSON array from PHP to jQuery AJAX

Currently, I am working on an experimental project where I need to search for a product in a MySQL database using the product name and retrieve the price in the 'price input' field and sell price in the 'sellprice input' field. You can ...

Encasing newly inserted child components within my designated slot

If I have a component with a single slot and instead of simply rendering all its children, I want to wrap each element individually, the following approach can be taken: Vue.component('MyElement', { render: function(createElement){ for (l ...

Changing class names when removing an element from an array

I have a data table where users can input information: <tbody> <tr class="wiring_details_6-73" id="wiring_rows_0"> <td colspan="2"> Wire Type: <select class="wire_selector_0" id="wiring_select_0" name="select_w ...

The challenge of harmonizing variables in PHP and JavaScript

I have a PHP script that generates an HTML table displaying data from a MySQL database. <?php include 'connexion.php'; session_start(); $idfirm = $_REQUEST['idfirm']; $namefirm = $_REQUEST['namefirm']; The table rows are ...

Cutting out the lowest identification that is not a certain object

A real-time counter showing the viewers of a news article on a website using Laravel Jetstream. .leaving(user => { this.participants.splice( this.participants.indexOf(user, 1)); }) .joining(user => { this.participants.push(user); ...