jQuery: Select the parent element of a focused form input and apply styling

Recently, I encountered a situation where I have a form containing a DIV along with 3 INPUTS, each enclosed within a LABEL element. My goal is to alter the background image of the DIV whenever an INPUT receives focus.

Due to limitations in navigating up the DOM using CSS, I'm seeking advice on writing a few lines of jQuery code to achieve this effect. Any suggestions would be greatly appreciated!

Thank you in advance!

Answer №1

$('div input').focus(function(){
    $(this).parents('div:eq(0)').addClass('customStyle');
}).blur(function(){
    $(this).parents('div:eq(0)').removeClass('customStyle');
});

To apply a particular visual style, define a new CSS class and update "customStyle" accordingly.

Answer №2

$('input').on('focus', function(){
    $(this).parents().eq(1).addClass('highlight');
}).on('blur', function(){
    $(this).parents().eq(1).removeClass('highlight');
});

Answer №3

For those looking for an alternative, jQuery closest can also be used.

closest( selector )
    .closest( selector )
    .closest( selector, [ context ] )
closest( selectors, [ context ] )
    .closest( selectors, [ context ] )

As explained in the documentation, closest retrieves the nearest ancestor element that matches the specified selector, starting from the current element and moving upwards in the DOM hierarchy.

http://api.jquery.com/closest/

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

Unresponsive JavaScript on specific element IDs

I'm experimenting with making three lines perform different animations: line 1 rotating 45deg and translating, line 2 becoming opaque, and line 3 rotating -45deg and translating. Check out my JS Fiddle here <a href="#"><div id="menu" onclic ...

JS client-side form validation involves communicating with the server to verify user input

I currently have an HTML form that is being validated on the client side. Below is a snippet of the code: <form id='myForm' onsubmit='return myFormValidation()'> ... </form> Now, I want to incorporate server-side valida ...

Troubleshooting JQuery Variable Overwriting Problem

Here is the code snippet I am working with: <script> $(document).ready(function() { var settings_image ={ url:"<?php echo site_url('/cms/editor/upload/images');?>", method: "POST", fileName: "file", returnType: ...

Expand the accordion to reveal all the content

I'm facing an issue with my accordion where a scrollbar appears in every content section. To fix this, I tried setting overflow: hidden in the CSS: .ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: hidd ...

Change the font style of individual characters within a string using CSS or JavaScript, instead of applying it to the entire

Is it feasible to assign a specific font to a particular character? I would like: #test_id{ font-family: "digitalfont"; font-family-of-, : "HelveticaNeue-Light"; } In order to set a font for a comma and a separate font for the rest, do I need to ...

Utilizing Facebook's JavaScript SDK to transmit variables to PHP using ajax

Thank you in advance for your attention. I am trying to utilize the Facebook js SDK to retrieve the user's name and id, and then send them to PHP on the same page (index.php). After successfully obtaining the username and id and storing them in two Ja ...

Why won't my sticky element function properly with the position attribute set to sticky?

Hey there! I've been diving into learning all about CSS positions and have nailed down most of them. However, for some reason, the sticky position just won't cooperate and is stubbornly acting like a relative one instead. Check out my HTML snipp ...

Looking to integrate the date, month, and year selection tags into the inline format

The Edit User Profile page includes a Birthday field, which is currently displayed vertically. I am looking to change the layout so that the Birthday field appears horizontally. Here is the code I am using: Within visitors/edit.html.erb, <%= simple_f ...

Simple Design Techniques for HTML Tables

I seem to be having trouble with the table styles when I include text in the <td> section: <td rowspan="3"> 30th May 2014 17:35... What could be the issue? <style type="text/css"> .tftable {font-size:12px;color:#333333;width:100%;borde ...

best way to display json data in a table-style list

I am utilizing a function that I call from AJAX to retrieve data in JSON format. My goal is to present all the data in a Table listview sequentially. While my function successfully retrieves the data, I am struggling with how to display it in the table vie ...

Ways to display title attributes when focused using jQuery?

Typically, title attributes in all browsers only appear when the mouse hovers over them. I am looking to also display them when users are focused on them via keyboard navigation. Unfortunately, without using JavaScript, this cannot be achieved solely throu ...

Can this functionality be accomplished using only HTML and CSS, without relying on JavaScript?

Image for the Question Is it possible to create a zoom functionality using only HTML and CSS, without relying on JavaScript? I need this feature for a specific project that doesn't support JavaScript. ...

"Uncovering the versatility of jQuery when selecting options with multiple values

Is it possible to check if a value of an attribute within a selector contains 'a', 'b', or 'c' in a single line? I tried using $('input[name]=a|b|c'), but unfortunately, that did not work as expected. Is there anothe ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

Tips for verifying a login modal on an asp.net webforms using jQuery?

I am currently working on an asp.net webpage that utilizes a modal bootstrap for user login. Upon clicking the Login button, it should authenticate the user and initiate a server-side method called "ExportToZip" to download a zip file. My issue lies in ens ...

Having trouble with the input range slider on Chrome? No worries, it's working perfectly fine

I'm currently facing an issue with an input range slider that controls the position of an audio track. It seems to work perfectly in Firefox, but in Chrome, the slider gets stuck and doesn't move when dragged. There is a function in place that up ...

Ensuring no null objects are present in the jQuery each function

In order to iterate through each key value pair in a JSON element and display it, I am encountering an issue where some of the keys have null values. As a result, using $.each is throwing an error: TypeError: obj is null I do not want to remove the null ...

Error message: RefererNotAllowedMapError - Google Maps API has encountered an issue with

I've integrated the Google Places API into my website to display a list of addresses, but I'm encountering the error detailed below. Encountered the following error when trying to use Google Maps API: RefererNotAllowedMapError https://developers ...

Is AJAX the way to load image files?

Is it feasible to load an image using AJAX alone, maybe from a form that includes or another method like drag-and-drop? I'm posing this question because all responses have been along the lines of: "No, it's impossible due to security concerns. ...

Receiving an error message stating that 'tinymce.init is not a function' while attempting to browserify tinymce

I am having trouble getting a basic tinymce call to work with browserify. When I load tinymce from a CDN, it works perfectly fine. Below is a simplified example of what I am attempting to do. // main.js var tinymceConverter = require('./modules/tinym ...