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

Achieving the extraction of a particular string from an HTML element using JavaScript

<input id="WD01B3" ct="CB" lsdata="{2:'WD01B4',4:'Any',20:'\x7b\x22WDA_TYPE\x22\x3a\x22DROPDOWN_BY_KEY\x22,\x22WDA_ID\x22\x3a\x22ABCA950297D2C0C432BAB9BB ...

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...

The dynamic page fails to export with a static export in NextJS, resulting in an output error: "

I'm struggling to export a route in my NextJS 14 project. I've set the output to export and all routes are exporting correctly except for the dynamic ones. The folder for the dynamic route is not showing up in the output folder The version of Ne ...

Struggling to implement the UI router into my Angular Framework

I've been working on a framework that is supposed to be router agnostic. While I've managed to make it work with ngRoute, I just can't seem to get it functioning with UI Router. Here's a snippet of the main app module: (function () { ...

"Step-by-step guide on adding and deleting a div element with a double click

$(".sd").dblclick(function() { $(this).parent().remove(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table width="750" border="0" cellpadding="0" cellspacing="0"> <tr> <t ...

How to send arguments to a callback function in Next.JS

Here's the code snippet I'm working with: import Router from "next/router"; import React from "react"; export default function MainIndex() { return (<React.Fragment> <h1>Main Index Page</h1> ...

Is it advisable to adjust the type of input control according to the drop down choice made?

I am currently working on creating an edit screen for users to update rows of data. One of the fields is a dropdown menu, while another field is an input labeled 'value'. Depending on the selection in the dropdown menu, I need to display differen ...

Incorporate a personalized JavaScript code segment during the Vue build process

I am currently working with Vue CLI and I need to include a custom javascript section in the default template when I release my project. However, I do not want this section to be included during the debugging phase. For example, I would like to add the fo ...

What is the best way to align a modal with a layout when it appears far down the components hierarchy?

Struggling with creating a React modal and facing some issues. Let's consider the structure below: React structure <ComponentUsingModal> <Left> <ButtonToActivateModal> ... </ButtonToActivateModa ...

Puppeteer encountered an error when trying to evaluate the script: ReferenceError: TABLE_ROW_SELECTOR was not defined

https://i.stack.imgur.com/PJYUf.jpg Recently, I started exploring pupeteer and node while using vscode. My goal is to log into a website and scrape a table. So far, this is what I have: (async () => { const browser = await puppeteer.launch({ headle ...

Tips for adjusting the height and border of Bootstrap tabs

I'm facing an issue with the modal and nav-tabs I created. There are a couple of problems that need to be addressed. Firstly, the tabs have excessive height and I've tried adjusting it using CSS height property, but it's not working as e ...

Showing pdf documents without relying on third-party software

Within my Angular application, I have integrated the following snippet into an HTML template: <embed src="../assets/AOK_T2DM.pdf" style="width: 100%;height: 500px" type="application/pdf"> The representation of this code ...

What is the difference in memory usage for JavaScript objects between Node.js and Chrome?

It's puzzling to me why the size of the heap is twice as large as expected. I meticulously constructed a binary tree with perfection. I suspect v8 recognizes that each node consists of 3 fields. function buildTree(depth) { if (depth === 0) return n ...

Issue: function is not a valid type (during mount)

Currently, I'm trying to add a feature that automatically closes all menus and modals when a user clicks outside of the specified area. Although I am successfully calling this.closeMenu(), an error is occurring stating that this.closeMenu is not reco ...

Clicking a link will trigger a page refresh and the loading of a new div

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> $(window).load(function () { var divs = $( #add_new, #details"); $("li a").click(function () { ...

How to include a Partial View or Child Page into a Master Layout using jQuery/Ajax in ASP.NET MVC

Currently, I am in the process of working on a CRM Admin panel that utilizes a left-hand side panel for navigation to various pages. Within this panel, there are buttons such as Home, About, and Contact. To streamline the layout, I have implemented a mast ...

Prevent the next ajax request from overwriting the parameter value set in the previous request

When my application makes multiple ajax requests, I encounter a problem where the original set of parameters used for each request get changed by subsequent requests, leading to errors. Let's take an example: Request A initially sets an index of 0 in ...

What is the best way to collapse a button in asp.net using javascript after setting it to hidden?

I have a scenario where I have 3 buttons in a row on my asp.net page. Using JavaScript, I am setting the middle button (ButtonSR) to invisible. However, I want the button below it to move up and take its place instead of leaving an empty space. ...

Modifying the scope variable does not trigger an update in the AngularJS directive

Recently, I created a small directive that wraps its contents with another template file. The objective is to transform the code like this: <layout name="Default">My cool content</layout> into this output: <div class="layoutDefault">My ...

Difficulty with Django's |safe template functionality

Issue with Django safe template functionality I attempted to utilize a textarea for rich text in the Django admin section, and everything seemed fine. However, when I try to display it on the front end using {{ date|safe }}, only a maximum height of appro ...