Changing the appearance of a radio button dynamically upon clicking

I am currently working on a dynamic pickup date form that utilizes radio buttons. My goal is to change the style of the selected value when a user clicks on it. Below is the code I have tried, but it has not been successful:

foreach ($period as $day){
echo '<label class="pickup-date" id="pickupdate"><input type="radio" value="'.$day->format('M-d-Y').'" name="pickup_date">'.$day->format('M') . ' <span>' .$day->format('d') . '</span> '. $day->format('D') .'<br/></label>';
}

Css

.pickup-date-tab label.checked{
background: #6d1f89 !important;
color: #fff; } 

jquery

$('#pickupdate').on('click',function(){
        $('#pickupdate').removeClass('checked');
        $(this).addClass('checked');
    });

The issue I'm having is that this code only works for the first button.

Answer №1

I have finally found the solution, all thanks to the amazing resources available on this website. It's so satisfying to resolve a related problem.

After some tweaking, here is my updated code snippet:

foreach ($period as $day)
                {
                    echo '<label class="pickup-date" id="pickupdate"><input type="radio" value="'.$day->format('M-d-Y').'" name="pickup_date"><div class="highlited">'.$day->format('M') . ' <span>' .$day->format('d') . '</span> '. $day->format('D') .'</div></label>';
                }

Here is the optimized jQuery for handling onclick events:

$(document).on('click','#deliverydate',function(){
    $('#pickupdate').removeClass('checked'); // Updated CSS property
    $(this).addClass('checked'); // Updated CSS property   
});

And don't forget the essential CSS styles:

.pickup-date input[type=radio]:checked + .highlited{
    background: #6d1f89 !important;
    color: #fff;
}

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

When checking if el.text() is equal to "string", it will return false, regardless of the actual content of the element being "string"

Looking at the code snippet below, it seems that the else block is always being executed instead of the if block. The alert confirms that the variable state has the value 'payment' as expected. var state = $('.check-state').text(); ale ...

Personalize the tooltip feature in highchart

I am looking to enhance the tooltip feature in HighChart. Currently, on hover of my bar chart, only one value is displayed in the tooltip. However, I would like to display three values instead. Here is a snippet of my code: $(function () { $( ...

Is .closest combined with :contains finding too many elements for my taste?

My goal is to highlight specific rows in a table that have a particular class assigned on $(document).ready. I attempted to use .closest with a tr to target individual rows, but instead it selects all rows and I'm unsure why. I've experimented w ...

Attach a function to a group of dynamically generated elements that share similarities and trigger an event

I am dealing with two dynamically created delete buttons that perform the same action on different objects. I want to bind a 'click' event to each button and have them run the same function when clicked. The code I currently have is as follows: ...

Pressing the Like Button triggers the transfer of a specific variable from PHP to jQuery

I have a piece of PHP code that I am using to display all users' posts, each with its own unique 'like' button: $sql = "SELECT * FROM posts"; $result = mysqli_query($con,$sql); while($row=mysqli_fetch_assoc($result)){ $post_content = $ro ...

Button On The Radio - Yii2 Basic App

When using radio buttons, the value is being populated. However, I am looking to display the name associated with that value. For my user_types table: id type status created_at 1 An Individual 1 ...

Guide on submitting form information to API controller

When using jQuery, form data is posted: $.ajax('API/Validate/Customer?column=1&rowid=2&vmnr=3&isik=4', { data: JSON.stringify({ headerData: $("#_form").serializeArray() }), async: false, cont ...

Working with jQuery: Creating multiple lightboxes using the same jQuery code

Is there a way to create a universal lightbox with the same code for all lightbox functions on the page using JQuery? $(document).ready(function() { $('.lightbox').click(function() { $('.backdrop, .box').animat ...

Customizing CSS to override Semantic React UI styles

Is there a way to customize the default Header provided by react semantic UI? Currently, I have placed my Header within a div so that I can apply custom styles. <div className="portfolioTitle"> <Header as="h1">Check out this amazing ...

Retrieving game information from the Hearthstone API

I'm currently working on developing a random Hearthstone card generator, but I've run into some issues with extracting JSON data from the API and converting it into a JavaScript object for use in my HTML. While I've confirmed that the API re ...

incorrect sequence of div elements appearing vertically

I'm having trouble organizing the header, page title, and navigation bar on my webpage. Despite my attempts to structure them correctly, they are not displaying in the desired order as shown below: https://i.stack.imgur.com/A3rQe.jpg The issue arises ...

Ensure that the form values are populated using redux-thunk and useSelector only after the data has been fully loaded

Hey there! I'm working with redux-thunk and using useSelector to fetch some data for populating a form. I've noticed that there is a delay in getting the data, so initially it's undefined. Then, once the data is loaded, the form doesn' ...

Steps to send an asynchronous AJAX request to the server-side within the JQuery validation plugin using the addMethod() function

Currently, I am in the process of developing my own framework using the JQuery validation plugin to validate CRUD forms both client-side and server-side. It is crucial that these forms are not static but rather created dynamically using "handlebar.js". Fo ...

Change the background color of cells according to the value they contain

I have a scenario where I am populating a table with random numbers, and I want the background color of each cell to change based on the value of the number in that cell. Since these numbers refresh periodically, I need the colors to update accordingly as ...

Is there a way to have one element automatically expand when another is selected?

I'm currently utilizing the date and time picker from . However, I need some assistance with the current setup. Currently, the date and time pickers are in separate input fields. In order to select a date, I have to click on the Date input field, and ...

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...

Adding click functionality to dynamically generated list items in jQuery and HTML

I'm encountering an issue while trying to assign click events to dynamically added HTML elements in jQuery. Despite extensive research within this community, I find myself more confused than before. Below is the snippet of code causing me trouble: v ...

Tips for fixing the issue of "The use of getPreventDefault() is outdated. Please use defaultPrevented instead."

When attempting to fetch data for a specific user from an SQL Server database using JSON data, I encountered an error message in the console: "Use of getPreventDefault() is deprecated. Use defaultPrevented instead." Additionally, the values are not bei ...

Struggling to add a line break in my code

class Test extends React.Component{ state={name: "John", numTimes: 2}; render() { let output = "" for (let i = 1; i <= this.state.numTimes; i++) { let evenOdd = i % 2 if (evenOdd === 0) { output += i + ". Hello " + this.state.name + ...

Learn the process of eliminating a class utilizing this JavaScript function

This script is designed to identify and manipulate elements with the class menu-option-set. When an element within this class is clicked, it adds the class "selected" to that specific element while removing it from all others in the list. My goal is to en ...