Accessing an image within a label using Jquery

I'm struggling with accessing the img tag when a specific checkbox is selected in order to add a particular class. I need help figuring out how to target the img tag.

<div class="row ">   
  <div class="col-md-5 col-md-offset-1 col-centered piege">
    <input type="checkbox" id="piega1" class="piege servizioSection2 " name="imgSection2"value="Piega By Wella Professionals">
    <label  class="piega labelStylingImg " for="piega1">
      <img src="img/piega1.png" for="piega1" alt="" class="img-responsive immaginePiega ">
    </label>
    <h1 class="immagineTitoloPiega">PIEGA BY WELLA PROFESSIONALS</h1>
  </div>
  <div class="col-md-5  col-centered piege">
    <input type="checkbox" id="piega2" name="imgSection2" class="piege servizioSection2" value="Piega By System Professionals">
    <label for="piega2" class="piega labelStylingImg">
      <img src="img/piega2.png" for="piega2" alt="" class="img-responsive immaginePiega">
    </label>
    <h1 class="immagineTitoloPiega">PIEGA BY SYSTEM PROFESSIONALS</h1>
  </div>
</div>

I want to add the borderRed class to the img if the checkbox is checked. Here's my code:

$(document).ready(function() {
  $(':checkbox').on('change', function (){
    if ($(this).hasClass('servizioSection2')) {
      if ($(this).is(':checked')){
        console.log('selected');
        var imgSelected = $(this).find('.immaginePiega');
      } else if ($(this).prop('checked', false)) {
        console.log('not selected');
      };         
    };
  })
});

Currently, I can log that it's selected but I'm having trouble accessing the img tag to apply the bordered class.

Answer №1

if :selected insert this

$(this).next().addClass('active');

otherwise add the following line

$(this).next().removeClass('active');

and feel free to customize your CSS with the class .labelStylingImg.active img For instance

.labelStylingImg.active img{ border: 3px dashed blue; }

Answer №2

If you want to achieve this effect, use the following technique:

var selectedImage = $(this).next().find('.imageFold');

Once you have selected the image, you can add a border like so:

selectedImage.addClass('bordered');

Alternatively, you can remove the border by using this code:

selectedImage.removeClass('bordered');

SEE THE DEMO IN ACTION

Answer №3

When there is a change, retrieve the label using the attribute "for" corresponding to the checkbox ID. The image is simply a child of this element (and they share the same attribute), making it a straightforward traversal.

For instance, simplifying:

$('#piega1').click(function(){ $('img[for=piega1]').addClass('borderRed'); });

Or tailored more precisely to your situation:

     $(':checkbox').change(function(e){
     var targetId = $(e.target).attr('id');
     var element = $('img[for=' + targetId + ']');
     if(element.hasClass('boderRed'))
         element.removeClass('borderRed');
     else
         element.addClass('borderRed');  });

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 best way to position a div on top of another within a container using Bootstrap?

I have created a div with a date picker inside a form for future fields, but the initial display is next to the table instead of above it. I've searched for solutions similar to my issue, but none seem to work for me. You can view the correct layout ...

The CSS code for adjusting width, text alignment, and margin for the <a> tag is not functioning correctly

Currently, I am only able to get color, padding, and font codes to work in my HTML. When I attempt to add width or align the text to the right, it does not seem to work. <a href="https://www.football.london/chelsea-fc/transfer-news/juventus-chelsea ...

Animate the transition between the icon and extended variant in Material-UI FAB

If you have a Material-UI FAB with the following code: <Fab size="medium" color="primary" aria-label="add"> <AddIcon /> </Fab> And you want to toggle to this other state: <Fab var ...

What is the best way to display an HTML message along with its tags on a printed

How can I display a message including HTML tags on a webpage? Specifically, I want the user to see this text exactly: <script>alert("hello world");</script> This includes the script tags as well. ...

Anchor link leading to an incorrect location

Sorry for the potentially silly question, but I'm struggling to figure out what's happening here. I'm currently working on a website and trying to create an anchor link at . I've placed the anchor just before in this code: <a name ...

Can CSS modules be used in conjunction with outside libraries?

I've incorporated a Slider library () into my React project. While regular CSS allows me to style the slider properly, I am facing issues when using css modules. The tsx file looks like this: import styles from './styles.module.css'; . . . ...

What is the best way to submit a form using ajax in PHP?

I'm experiencing an issue with my ajax form submission. I have set up a jquery alert to display when the submission is successful, but it is not showing up. I suspect that the submission is unsuccessful. Can anyone help me figure out why? Here is the ...

The form features a "Select all" button alongside a series of checkboxes for multiple-choice options

I am facing difficulties trying to get the "Select all" and "Remove all" buttons to function properly within my form. Whenever I remove the "[]" (array) from the name attribute of the checkboxes, the JavaScript code works perfectly fine. However, since I n ...

Verify if a checkbox is selected using an if statement in a Django template

I am currently working on a registration form that requires the user to check a checkbox in order to accept the terms and conditions before they can submit the form. The submit button should be disabled until the checkbox is checked, at which point the but ...

Creating slanted lines using CSS / Bootstrap 3

I'm trying to create a webpage with slanted lines. Is it possible to set an angle of 20 degrees using three div elements? Currently, I have one div for the logo at the center and another for the navigation bar. I want the navigation bar to align with ...

Retrieving an array using the $.post() method

I am utilizing the following code: $.post('fromDB.php', function(data) { eval(data); console.log(data); updateTimer(); }); In order to retrieve arrays from PHP. This is what PHP returns: var todayTimeMinutes = [0, 45, 35, 25, 40, 0 ...

Using ion-icon inside a clickable ion-card while applying float: right does not render properly

I am facing an issue with a list of ion-cards that have clickable icons appearing when you hover over them. The problem is that due to the floating nature of the icons, they are not positioned correctly (as shown in the image below) and end up getting cove ...

transform the encoded JSON data into a JavaScript array

When it comes to sending data from PHP to JavaScript using json_encode, the data structure looks something like this: [{"albumid":"ASaBFzCtl8","albumname":"anni","type":"3","access":"2","itemcount":"2"},{"albumid":"EmgsZ43ehT","albumname":"testalbum","typ ...

What's the reason the element inside the <div> is not displayed when a value is selected in the dropdown box?

I am perplexed as to why the element inside the does not appear when a value is selected in the drop down box. However, it works perfectly fine in JSFiddle: JSFiddle Below is my HTML code and Jquery script that functions properly in my own system: <t ...

Styling with CSS to create a division that appears below another

I am working with HTML code that looks like this: <div class='box'> <div class='left'>content left</div> <div class='right'>content right</div> </div> Now, for smartphone devices, ...

The SimpleHTTPServer is causing Google Maps Places Autocomplete feature to malfunction

Currently, I am implementing a location search feature along with form auto-fill using the google.maps.places.Autocomplete functionality. While accessing the HTML file directly (file:///location.html), everything is functioning as expected. However, when ...

Issue with Second Accordion Panel not refreshing

Within my accordion setup, the initial panel showcases a selection of icons. Upon choosing one of these icons, it triggers the display of one of three panels in place of the second accordion panel, based on the selected icon. The issue seems to be rooted i ...

What is the best way to extract the elements within a form using Angular and automatically add them to a list?

Recently, I started learning Angular and decided to create a simple list feature. The idea is to input an item name and price, then click "Add item" to see it added to the list below. I have all the code set up correctly, but for some reason the name and ...

Can you explain the process of selecting a SubMenu Item that is a hover link in IE using C# and Selenium?

I have been scouring various topics on Stack Overflow and other platforms for days in search of a solution to my problem, but so far, I have had no luck. I am facing an issue with automating a website using C# Selenium where Webdriver is unable to click on ...

Utilizing Dynamic URLs in Kendo for Data Binding or Attributes on List Elements

I am facing an issue with routing two menu items conditionally using Kendo Jquery/MVVM. Originally, I had set the value in a data-href tag and it was displaying the URL correctly. However, I now need to dynamically load a URL based on certain conditions. T ...