Graphic selectors: a new take on radio buttons

I've been attempting to make this work, but it's not functioning correctly.

Below is the CSS code:

.input_hidden {
    position: absolute;
    left: -9999px;
}

.selected {
    background-color: #000000;
}

#carte label {
    display: inline-block;
    cursor: pointer;
}

#carte label img {
    padding: 3px;
}

The HTML section looks like this:

<div id="carte">
    Select a card:<br>
    <input type=radio name="carte" id="cart1" class='input_hidden' />
    <label for="cart1">
       <img src="cart1.jpg" alt="card1" />
    </label>
    <input type=radio name="carte" id="cart2" class='input_hidden' />
    <label for="cart2">
       <img src="cart2.jpg" alt="card2" />
    </label>
    <input type=radio name="carte" id="cart3" class='input_hidden' />
    <label for="cart3">
       <img src="cart3.jpg" alt="card3" />
    </label>
</div>

Lastly, the JavaScript snippet is as follows:

$('#carte label').click(function(){
    $(this).addClass('selected').siblings().removeClass('selected');
});

While applying the selected class works on an image, the part of the script that should be assigning the class seems to be ineffective. Are there any alternative methods for managing classes with these images? Your assistance is greatly appreciated.

Answer №1

Should jQuery be your choice for this task?

If you have modern browsers, you may consider using pure CSS to resolve the issue: http://jsfiddle.net/VSR86/4/

Here is the HTML:

<div id="carte">

    <label>
        <input type="radio" name="carte" value="cart1" >
        <img src="http://placekitten.com/100/100">
    </label>
    ...

And the accompanying CSS:

label input + img {
  border: 10px solid transparent;
}

label input:checked + img {
  border: 10px solid blue;
}

Note that some javascript workaround will be needed for compatibility with IE8 and older versions.

For more information on :checked pseudo-class in CSS, visit: https://developer.mozilla.org/en-US/docs/Web/CSS/:checked

Solution for IE8

Update the CSS as follows:

label input.checked + img,
label input:checked + img {
  border: 10px solid blue;
}

Below is the JavaScript fallback code:

if(/* this browser is IE8 or worse */){

  $(document).on('click','label:has(input[type="radio"])',function(){
      var $r = $(this).find('input');
      adjustRadio( $r.attr('name'), $r.val(), 'checked');
  });

}


function adjustRadio( name, value, className ){
  // wait for other event handlers to run
  setTimeout( function(){
    $('input[type="radio"][name="'+name+'"]').each( function(){
      var $r = $(this);
      $r.toggleClass( className, $r.val() === value );
    });
  },1);
}

Answer №2

If you want to simplify things, consider using the toggleClass function.

For more information, check out: http://api.jquery.com/toggleClass/

In case you're looking for a live example, here's a fiddle for you:

http://jsfiddle.net/8B3SW/1/

$('#carte label').click(function(){
    $(this).toggleClass('selected').siblings().removeClass('selected');
});

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

Determine whether an input is currently in a "checked" state

I am working with this simple HTML layout: <fieldset> <input/> <label></label> <div class="toggle_box"> <div class="switch"></div> </div> </fieldset> My goal is to achieve the ...

Error in tabs.onUpdated argument in Firefox WebExtensions

I am currently working on developing a straightforward webExtension for Firefox and I would like to implement tabs.onUpdated with a filter. I found an example on the Mozilla website that I decided to use: const pattern1 = "https://developer.mozilla.org/*" ...

Using AngularJS Typeahead with restrictions on $http requests

I have been attempting to restrict the number of results displayed by Angular Bootstrap Typeahead during Async calls, but unfortunately, it does not seem to be functioning as expected. <input type="text" ng-model="asyncSelected" placeholder="Locations ...

I'm receiving the error message "app.get is not a function" when using Express.js. What could be

Having trouble understanding why I am getting an error: app.get is not a function in the upload.js file with the provided code snippet. In my index.js file, I have set up everything and exported my app using module.exports = app. I have also used app.set( ...

Struggling to align the push menu properly within the Bootstrap framework

I am currently utilizing Bootstrap as my UI framework and attempting to create a push menu on the left side of the page. While I have made progress towards achieving this goal, there are some bugs in the system that I am encountering. Specifically, I am ha ...

What is the best way to display a child div without impacting the position of other elements within the same parent container?

As I work with a div html tag within a login form, encountering an error inside this form has presented a challenging issue. The error div sits at the top of its parent div, and ideally, upon activation, should remain within the form div without disrupting ...

Finding alternative solutions without using the find() method when working with Angular

How can I use an equivalent to find(".class") in AngularJS? I came across this solution: //find('.classname'), assumes you already have the starting elem to search from angular.element(elem.querySelector('.classname')) I attempted to ...

Detecting Specific Web Browsers on My Website: What's the Best Approach?

My website is experiencing compatibility issues with certain browsers, such as Firefox. I want to display a message when users visit the webpage using an unsupported browser, similar to how http://species-in-pieces.com shows a notification saying "Works ...

NextAuth.js in conjunction with nextjs version 13 presents a unique challenge involving a custom login page redirection loop when using Middleware - specifically a

I am encountering an issue with NextAuth.js in Nextjs version 13 while utilizing a custom login page. Each time I attempt to access /auth/signin, it first redirects to /login, and then loops back to /auth/signin, resulting in a redirection loop. This probl ...

Mastering the Art of Harnessing External Templates in Meteor Mantra

I have been diving into the Mantra style guide () in order to integrate it with meteor. What confuses me is determining the "right" approach for using external templates with meteor and mantra. Specifically, I'm unsure about handling CSS and JS files. ...

Images for navigating forward and backward in a jQuery datepicker

I'm experimenting with setting custom images for the previous and next month buttons. I attempted to utilize the prevText / nextText options of the datepicker in order to include a span with my own CSS class definition. However, this resulted in the c ...

Exploring various ways to implement HTTP GET requests within the PrimeVue DatatableUsing a mix

I am facing a challenge where I need to use different GET requests to populate my Datatable with data from separate tables in the Database. Despite trying different approaches, I am unable to figure out how to make this work successfully. I have realized t ...

How can a div tag and its class be nested using CSS in Angular?

Can someone help me with nesting a div tag with the "error" class in CSS? <div [class]="{error: condition}">{{ message }}</div> I want to know how to have the .error selector inside the div selector in the CSS file. Note: The error ...

An issue with the AngularJS [$parse:syntax] error has been identified when using specific data in the

I encountered an issue when attempting to create an AngularJS ui-grid table with data that includes a '(' and then whitespace before the closing ')' within a string. This resulted in an AngularJS error message: Syntax Error: Token &a ...

The specified subpath './lib/tokenize' does not match any defined "exports"

As a newcomer to React, I've been facing some challenges while trying to get started. Despite searching on Google and other platforms, I couldn't find a solution to my problem. I was attempting to run code from a YouTube channel called Lama Dev b ...

Utilizing Nicknames in a JavaScript Function

I'm dealing with a function that is responsible for constructing URLs using relative paths like ../../assets/images/content/recipe/. My goal is to replace the ../../assets/images section with a Vite alias, but I'm facing some challenges. Let me ...

Svelte Material UI Circular Progress Indicator encountering issues

I'm having trouble getting the Svelte Material UI Circular Progress indicator to function properly. I attempted to implement it in my project initially, and then decided to try it out in Code Sandbox using the provided code from the documentation. How ...

JavaScript: Populating an Array with Image URLs Using a Loop

My image gallery project has hit a roadblock and my JavaScript skills are not up to par. Maybe it's time to brush up on the basics with a good book from the library. Here's what I want to achieve: 1. Create an array of URL's for each imag ...

The Chrome extension takes control of the new tab feature by redirecting it to a custom newtab.html

I have a website https://example.com where users can adjust their site preferences, including enabling night mode. To enhance the user experience, I developed a Chrome extension for https://example.com that transforms Chrome's new tab with a custom ne ...

Retrieve a specific nested key using its name

I am working with the following structure: const config = { modules: [ { debug: true }, { test: false } ] } My goal is to create a function that can provide the status of a specific module. For example: getStatus("debug") While I can access the array ...