Unique radio button styled as a custom div

Struggling with creating a div on my website that functions like a radio button, similar to the layout seen on . The div should display product name, price, and image.

Appreciate any solutions or suggestions. Currently using Bootstrap 4 and JQuery/Javascript for development.

Answer №1

One way to easily handle button selection is by using a specific class to highlight the selected button. By toggling this class on button click events, you can achieve a simple and effective solution:

(1) Remove the highlighting class from all buttons.

(2) Add the highlighting class to the clicked button.

This method is straightforward, stylish, and gets the job done.

$('.myradio').click(function(){
  $('.myradio').removeClass('myactive');
  $(this).addClass('myactive');
});
.myradio{display:inline-block;}
.myactive{background:dodgerblue;color:white;}

/* Additional styling */
.myradio{padding:3px 7px;margin-left:10px;border:1px solid dodgerblue;border-radius:5px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="myradio myactive">One</div>
<div class="myradio">Two</div>
<div class="myradio">Three</div>

If desired, assigning unique IDs to each button's div element can help in tracking the currently selected button. This information can be useful for identifying the active button and potentially transmitting relevant data elsewhere.

Answer №2

To enhance user experience, allow users to click on the label associated with the radio button. This triggers an action in the surrounding div, giving the impression that the div itself is being clicked. Remember to use the "for" attribute in the label to link it to the input's id.

By assigning the same name attribute to all radio buttons and distinct ids (e.g., name="myradio"), clicking one will deselect others and select only the clicked option. This consistent naming convention enables you to retrieve and utilize this data as needed.

CSS plays a crucial role in this setup. By targeting checked inputs (input[name="myradio"]:checked) and using the "+" selector to target the subsequent element (.clickable or .clickable .checked-box), we achieve the desired effect.

Included in the example is a snippet of jQuery code that logs the id of the selected box in the console for data tracking purposes.

For further information on the CSS selector used, refer to this link:

https://www.w3schools.com/cssref/sel_element_pluss.asp

<!DOCTYPE html>
<html>
    <head>
        <title>Code Sample</title>
        <style>
            // CSS styles omitted for brevity
        </style>
    </head>
    <body>
        <!-- Code sample for inline product selection boxes -->
        <div class="div-inline-list">
            <div class="product-container">
                <input id="prod1" type="radio" name="myradio">
                <label for="prod1" class="clickable"><span class="checked-box">&#10004;</span></label>
                <p class="product">Prod 1</p>
            </div>
            <div class="product-container">
                <input id="prod2" type="radio" name="myradio">
                <label for="prod2" class="clickable"><span class="checked-box">&#10004;</span></label>
                <p class="product">Prod 2</p>
            </div>
            <div class="product-container">
                <input id="prod3" type="radio" name="myradio">
                <label for="prod3" class="clickable"><span class="checked-box">&#10004;</span></label>
                <p class="product">Prod 3</p>
            </div>
        </div>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $('input[name="myradio"]').change(function(){
                    console.log("#" + $('input[name="myradio"]:checked').attr('id'));
                });
            });
        </script>
    </body>
</html>

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

Accordion feature exclusively toggles the initial item

I am having an issue with the code in my index.php file. Only the first item in the accordion menu is showing up correctly. When I click on "Status" or "Repeated", I expect to see the sub-menu of the clicked item, but instead, I am getting the result from ...

When submitting the form, does it trigger the opening of the PHP file?

Let's get straight to the point. Before anything else, I want to say THANKS IN ADVANCE. So, here's what's happening: When I submit the form I created, it goes through the submission process and all, but then it redirects the page to the PHP ...

Scrolling background for a nested Bootstrap modal

I am facing an issue with a modal that has a lengthy content and a button to open another modal. Once the inner modal is closed, the outer modal becomes unresponsive. It fails to scroll and instead, the background starts to scroll. While I have come acros ...

Tips for updating the text of an HTML element without deleting its children using JavaScript

Currently, I am implementing a code snippet to translate elements that contain the data-i18next attribute: const elementsToTranslate = document.querySelectorAll('[data-i18next]'); for (let i = 0; i < elementsToTranslate.length; i++) { ele ...

Create a custom countdown using Jquery and Javascript that integrates with MySQL and PHP to display the datetime in the format Y-m-d

Hey there, I'm looking to create a countdown script using dates in the format (Y-m-d H:m:s). The goal is to retrieve the current_datetime and expire_datetime in this format and incorporate them into some JavaScript or jQuery plugin to display a countd ...

Eliminating the gray background using CSS

How can I remove the gray background that automatically appears in my CSS header? .header { padding: 60px; margin: 20px auto auto auto; width: 1400px; border-radius: 10px; text-align: center; background: # ...

Troubleshooting issue: Bootstrap 4 Card trimming absolute content within div

Having trouble adding a rounded icon to the top center of a card, but part of the icon is getting cut off. Any suggestions? .header-icon-round { width: 60px; height: 60px; border-radius: 30px; font-size: 30px; background-color: #fff; ...

Is there a way to perform unit testing on JavaScript code that runs following the completion of a CSS transitionEnd event

I am working with a bootstrap modal window and using qunit+sinonjs (fake timers). However, I have noticed that one element (div class='modal-backdor') remains on the page despite my efforts. You can view the issue here: http://jsfiddle.net/valu ...

Animate a div once the parent section becomes visible while scrolling

I previously had this function working, but it seems that I have somehow messed it up in the process. My current setup includes a scroll hijack feature that navigates users to a new section or card each time they scroll. The script adds a visible class w ...

Is there a way to update the value of an element that is continuously changing through a setInterval() function when hovering the mouse over it?

I am currently a novice working on developing a pomodoro timer. At the moment, when you click the button to start the timer, it switches to displaying the remaining time once activated. One of the features I want to implement is the ability for users to h ...

Issue with JavaScript: array maximum function malfunctioning

Here is the javascript code I am working with: http://jsfiddle.net/MvWV7/5/ The goal is to have users fill in the inputs starting with 1. Once they type 1, the next value should be 2 (and not any other number). I am attempting to store the input values i ...

A creative CSS technique to eliminate borders from ul elements without relying on the calc() function

I'm currently using the top bar component from Zurb Foundation and have added a 1px border at the top and a 3px border at the bottom of the nav tag. However, I am facing height issues because the ul menu inside is set to 100% height. What would be th ...

Arrange elements in a vertical layout and align them to the left when they exceed the boundaries of their container

I am seeking a solution for laying out my design, similar to the one shown in this image Essentially, I have a container with a fixed height of 300px. I want to display a list vertically with each item taking up a width of 33%. If the list becomes too lon ...

The bootstrap-select selectpicker is encountering issues selecting options within the dropdown menu

I'm having trouble getting the bootstrap-select plugin to work inside a dropdown-menu. The select option is not appearing for me. To prevent the dropdown-menu from closing when clicked, I added this jQuery code: $(document).on("click", &qu ...

Show a decimal value as an integer in Razor

Looking for assistance with razor code: @Html.DisplayFor(model => item.sepordan_melk_foroshes.ghamat_total) The current output is: 123.00 How can I remove the decimal and display it like this?: 123 Any help with this would be greatly appreciated. ...

Bootstrap 3 Full-Width Responsive Image Overlapping

I have designed a grid layout with col-md-7 on the left side and col-md-5 on the right side. The images in the col-md-5 are responsive and have a full-width of col-md-12. <div class="container"> <div class="row"> <div class="col ...

Using the jQuery/JavaScript operator is similar to the SQL LIKE query with the wildcard %

Is there a way to search for a specific part of my input using JavaScript/jQuery? I've tried two different methods, but neither yielded any results. <script type="text/javascript> $("#button").click(function () { $("#DivToToggle").toggle(); ...

Implementing scrolling functionality within a nested container

I need help with getting a nested container (.widget2) to scroll while still keeping the borders intact. Currently, the inner container is scrolling past the bottom edge of the parent container, and the scrollbar isn't displaying correctly. If you w ...

Are Firefox and Internet Explorer experiencing issues with CSS rendering accurately?

Experiencing some problems with IE and Firefox CSS To see the issue, visit Check it out in Chrome - it's displaying correctly there But when you view it in IE or Firefox, it's acting strange. Am I making a mistake somewhere? Any help would b ...

What is the reason behind my styled component only displaying the final state in its className logs?

Here is my implementation using styled components with the version "@types/styled-components": "^5.1.26" and I'll provide you with an example of my code. // index.tsx import React, { useEffect, useState } from 'react'; i ...