Modifying the label focus does not alter the CSS style

I'm struggling with a simple form where I want to highlight the focused labels by changing their background colors. However, the jquery code doesn't seem to be working as expected. Despite no errors showing up in the console, the functionality isn't behaving as intended. Can someone provide some help on this issue?

<form action="" method="POST" id="qrForm">

    <label for="enter1">Enter<input id='enter1' type="radio" name="enter"></label>
    <label for="enter2">Exit<input id='enter2' type="radio" name="enter"></label><br>
    <label for="device1">Took a device<input id="device1" type="radio" name="device"></label>
    <label for="device2">Returned a device<input id="device2" type="radio" name="device"></label>
</form>

<script>
    $("label").focus(function(){
        $(this).css('background-color', '#00CC66');
    });
</script>

While I could use the approach of adding/removing a class to achieve the desired result, I find it puzzling why the current setup isn't functioning correctly.

Answer №1

Why opt for JavaScript when CSS can do the job?

label:focus {
    background-color: #00cc66;
}

If you want your label elements to be focusable, remember to add tabindex=0. This ensures that when a label is clicked, the focus shifts to the associated input element.

Another approach is using the CSS next sibling selector like this:

HTML:

<input type="text" id="foo" class="foo"><label for="foo">label</label>

And in CSS:

.foo:focus + label {
    background-color: #00cc66;
}

You can also experiment with various markup and CSS selectors to achieve desired effects.

Answer №2

To activate the focus for a label, use .focus() on the input element instead of directly on the label. Take a look at this example:

$("input").focus(function(){
    $('label').css('background', '#00CC66');
});

Alternatively, you can also achieve this with the following code:

$("input").focus(function(){
    $(this).closest('label').css('background', '#00CC66');
});

Answer №3

Attempt this approach since using focus on label is not allowed -

$( "form input:radio" ).focus(function(){
            $(this).parent('label').css('background-color', '#00CC66');
        });

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

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

What is the best way to dynamically swap out an image within an element?

Is there a way to dynamically replace this image without deleting the HTML SVG element and re-rendering it? xlink:href="http://missosology.info/forum/download/file.php?avatar=11666_1307312313.jpg" CODE: https://jsfiddle.net/bfv17f0e/ <svg class="clip ...

Retrieve all existing Session Variables that start with a specific prefix

Hey everyone, I have set up a series of session variables using an id as part of the name. For example, I have these variables: $_SESSION['test_variable_1']; $_SESSION['test_variable_2']; $_SESSION['test_variable_3']; I&apos ...

Updating attribute values in a dynamic JSON file with Node.js: A step-by-step guide

My task involves checking if the key in input.json file matches any key in the server.json file, and then updating the value in the server.json file. The challenge lies in the fact that the server.json file is dynamic with an unpredictable structure contai ...

Custom Angular directive for collapsing sub menus with CSS

I found a helpful article on creating collapsible menus and submenus using only Bootstrap and custom code for Angular 2, 4, 5, 6. I've been able to implement the logic successfully, but I'm facing an issue with multiple menus where clicking on an ...

Ways to receive JavaScript console error messages to aid in debugging your code

Currently, I am developing a Web Application and facing an issue with capturing console errors. Specifically, I need to capture errors related to network connectivity issues, such as when the network is down or slow causing responses from the server to be ...

sending an alert via a function's return statement

Could you explain to me why this code isn't functioning properly? When I call s.A, the alert message doesn't appear. Can you help me understand why? var s = { A: function () { alert("test A"); }, B: function () { alert("test B"); } }; ...

What is the alternative method for reading an HTML text file in JavaScript without utilizing the input type file?

Within the assets folder, there is a text file containing HTML that needs to be displayed within a specific component's div. Is it possible to retrieve the contents of this file and assign them to a string variable during the ngOnInit lifecycle hook ...

Issue with accessing container client in Azure Storage JavaScript library

When working on my Angular project, I incorporated the @azure/storage-blob library. I successfully got the BlobServiceClient and proceeded to call the getContainerClient method, only to encounter this error: "Uncaught (in promise): TypeError: Failed ...

JQuery is unable to initiate a keyup event

I am currently utilizing jQuery in a web application. On one of my pages, I have set up an event listener for keypresses as shown below: document.addEventListener('keyup', function (event) { event.preventDefault(); var key = event.k ...

Creating a JSON hierarchy from an adjacency list

I am currently working with adjacency data that includes ID's and Parent ID's. My goal is to convert this data into hierarchical data by creating nested JSON structures. While I have managed to make it work, I encountered an issue when dealing ...

swapping out an external CSS file in React for a new CSS file

My React app is quite large and includes four main CSS files (darkLTR, lightLTR, darkRTL, lightRTL), which may not be the most efficient setup. The templates were provided by my boss, and I was instructed to use them instead of Material UI, which I initial ...

I seem to be struggling with hiding/showing a div element. Can you figure

I am in the process of creating a gallery that will display a div with images when a button is clicked. The issue I am facing is that when I have two buttons, only the last images are clickable. It's a bit difficult to explain, but you can see it in ...

Resizing rectangular images with CSS/Bootstrap into perfect squares

Imagine there is a rectangular image with dimensions of 1400px (height) x 700px (width). I am looking to turn it into a square while maintaining its original proportions and having white sides added. I specifically do not want to crop the image - I want it ...

Creating a three-dimensional representation by projecting onto the surface of a sphere in ThreeJS

3D animation is a realm filled with numerous terms and concepts that are unfamiliar to me. I am particularly confused about the significance of "UV" in 3D rendering and the tools used for mapping pixels onto a mesh. I have an image captured by a 360-degre ...

Effective sparse translation between whole numbers

I am in the process of developing a specialized regular expression engine that utilizes finite automata. My goal is to manage numerous states, each equipped with its own transition table mapping unicode code points (or UTF-16 code units; I have yet to fina ...

Persistent Gap at the Top of the Page

I'm facing a simple issue that I can't seem to solve. At the top of my page, there's a white space about the width of a finger, and when inspecting it, nothing seems to be highlighted. @import url('https://fonts.googleapis.com/css?fa ...

What is the best way to prevent duplicates in a Material-UI dropzone area?

Currently, I am utilizing the Material-UI Dropzone component from https://yuvaleros.github.io/material-ui-dropzone/ and my goal is to prevent users from uploading duplicate files that have been previously uploaded. I attempted using an onchange function t ...

Incorporating a technique for aligning text towards the right as the number of characters or digits expands

I'm designing a game user interface with a money indicator. Let's imagine the player has 0 dollars in their wallet, it should appear like this: https://i.stack.imgur.com/35eoh.png Please note that it is located in the upper right corner. The p ...

Several directories for viewing in Node.js with Express

I have been researching different solutions, but I am still unsure about how to effectively integrate Express with multiple view folders. Imagine an Express application divided into distinct parts, each organized in its own subfolder: app +partA + ...