How to style focused input using Vue2

I have a form that contains multiple input fields, and I want to dynamically add a class to the label tag of the focused input and remove it when another input is selected.

Initially, I tried the following code:

onInputSelected: function(e) {
     var label =  e.target.previousElementSibling;
     label.classList.add('highlight');
}

However, I later realized that I needed to remove the class from one input and add it to another when the focus changes.

Update:

I managed to find a solution, but it seems a bit complex :)

data: {
    allInputs: document.getElementsByTagName('input')
},
methods: {
    onInputSelected: function(e) {
        e.target.previousElementSibling.classList.add('highlight');
        [].forEach.call(this.allInputs, function (currentValue, index) {
             if(currentValue.name ==  this.name) {
                 return;
             }

              currentValue.previousElementSibling.classList.remove('highlight');
        }, e.target);
     }
}

Answer №1

Initially, it seems like you are not providing a clear explanation of your objectives. Additionally, since you have already found a solution, consider optimizing your code. Furthermore, I recommend trying to use el.closest.

const input = document.getElementById('yourInput');
const label = input.closest("label");
// or if you want to add ids to labels
const label2 = input.closest("#yourLabel");

Check out the documentation here

This approach will make your code more robust. In your current implementation, there is a potential risk that if someone modifies the HTML structure, your code may no longer function properly.

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

What is the process for connecting two scripts together?

Purpose : I am currently working on a Firefox add-on with the goal of tracking the online status of my team members in a game. Current Progress : I have developed an initial JavaScript script that runs upon opening the browser. This script creates and ...

Sharing data between different JavaScript files using Knockout.js

I am working with two JavaScript files named FileA.js and FileB.js. Within FileA.js, there is a function called Reports.CompanySearch.InitGrid: function InitGrid(viewModel, emptyInit) { var columns = [ { name: 'CompanyName', ...

Using Flask and AngularJS: Managing Scope in a Controller with Flask Templating

Currently, my primary objective is to create a table with sortable columns. While following a tutorial and attempting to implement it into my project, I have encountered an issue. It seems that the structure of my code will not allow this functionality to ...

Authentication through Auth0 login

After successfully registering a user in Auth0 for login purposes (found in the Users section of the dashboard), I implemented the following code to authenticate the user using an HTML form with username and password fields: public login(username: string, ...

I am interested in utilizing angular 4 ng2-ui/map with places-auto-complete functionality that is restricted to a specific country

Check out my code snippet below: <input class="form-control" placeholder="Pickup Location" places-auto-complete (place_changed)="pickupChanged($event)" formControlName="pickup_location" [types]="['geocode']" /> I am trying to figure out ...

AngularJS static list with dynamically changing content

Seeking inspiration on creating an AngularJS information monitor with a maximum of 6 rows. The display should show new rows at the top, pushing out the oldest row from the bottom when there are already 6 rows visible. Rows can also disappear unexpectedly. ...

Is it necessary to include my library dependencies in the devDependencies section if I am only planning to publish the library bundle?

When creating a bundle for a library, should the library dependencies be placed in devDependencies? I am developing an NPM library in TypeScript that relies on several dependencies, including React components. As part of the build process, we compile to J ...

Tips for fixing the TS2345 compilation error when working with React

Attempting to implement the setState method in React has resulted in a compile error. Any solutions to this issue would be greatly appreciated. Frontend: react/typescript articleApi.tsx import axios from 'axios'; import {Article} from '../ ...

Creating a vibrant and mesmerizing inward spiraling rainbow of colors on canvas using JavaScript

After coming across an image that caught my eye, I was inspired to recreate it using canvas: https://i.stack.imgur.com/fqk3m.png I've attempted drawing arcs starting from the center of the screen, but I'm struggling with getting their paths acc ...

Keep track of the user's email address as they complete the form

I currently use a Google Form to gather information from employees who work in remote locations Emp No * Punch * Customer details / mode or travel All the data collected is stored in a Google spreadsheet structured as follows: Timestamp Emp No Punch ...

How can these lines be drawn in a simple manner?

I have been using the div tag to create a line, but I'm looking for an easier solution. If you have another method in mind, please share it with me. #line{ background-color:black; height:1px; width:50px; margin-top:50px; margin-left:50px; f ...

Issue encountered when setting up Webpack development server resulted in the failure to generate

Is anyone else experiencing difficulties when trying to create a static folder named "dist"? Package.json "scripts": { "start": "webpack-dev-server --open", "dev": "webpack --mode development --watch ./frontend/src/index.js --output ./frontend/static/fr ...

Testing a Nuxt application using Jest and Sinon: A comprehensive guide

Currently, I am in the process of adding a unit test to a Nuxt application using Jest and Sinon for stubbing functions. My main goal is to stub Axios get calls. Here's how I create an instance: return shallowMount(BarChart, { stubs: { highchart ...

The issue with ng-change is causing the previously selected drop down option to be cleared

After successfully implementing live searching with ng-change, I encountered an issue with a pre-selected drop-down box. Despite setting the selected="selected" attribute to make option three the default selection, the drop-down box jumps to the top optio ...

What is the reason that modifying a textarea causes the AJAX loading of content to be interrupted?

I am currently developing a feature that allows users to quote comments on my website. When a user wants to reply to a specific comment, they can simply click on the "quote" button next to that comment. This action triggers a script that adds the quoted co ...

What changes should I make to my save function in order to handle both saving and editing user information seamlessly?

My goal for the save function is to achieve two tasks: 1. Save user in table - Completed 2. Update user in table - In progress Save function snippet: var buildUser = function () { $('#save').click(function () { var newUser = {}; ...

Assigning websockets to a global variable may cause them to malfunction

I'm utilizing websockets in conjunction with JavaScript and HTML5. Here is the code snippet I am currently working with: <input type="text" onFocus="so = new Websocket('ws://localhost:1234');" onBlur="so.close();" onKeyUp="keyup();"> ...

What is the best way to access the form button inside a div element?

Here is the code snippet for my form: <form accept-charset="utf-8" action="https:example.com" method="get" name="test"> <div class="classy"><input type="button" class="buttonE ...

Creating Dynamic Height for Div Based on Another Element's Height Using ReactJS and CSS

I'm attempting to set a fixed height for a div in order to enable overflow scrolling. However, I am encountering issues as I am using JavaScript within a useEffect hook to accomplish this task. The problem is inconsistent as sometimes the height is se ...

Utilizing the $.ajax method along with the onreadystatechange event

Is there a way to use the onreadystatechange event of the underlying XMLHttpRequest in JQuery's (version 2.0.2) $.ajax(...) function to trigger synchronous ajax requests for displaying accurate status indications during long-running processes? It seem ...