Emphasize the checkbox

In my table, I have radio buttons that should turn the neighboring cell green when clicked. Using JQuery, I added a "highlight" class on $.change event to achieve this effect.

However, I encountered an issue where some radio buttons load with the "checked" attribute already set. How can I use JQuery to find all radio button elements with the "checked" attribute upon page load? Below is my attempt, which doesn't seem to work as expected.

JQUERY

$('input:radio').ready(function() {
    if($(this).is(':checked')){
        $(this).parent().addClass('highlight');
        var $td = $(this).parent();
        $td.siblings().removeClass('highlight');
        $td.next().addClass('highlight');
    }   
});

CSS

#sort td.highlight {background: #33FF99;}

Answer №1

To iterate over all the radio buttons, utilize the each method:

$(document).ready(function(){
    $('input:radio').each(function(index, element) {
        if($(element).is(':checked')){
            $(element).parent().addClass('highlight');
            var $td = $(element).parent();
            $td.siblings().removeClass('highlight');
            $td.next().addClass('highlight');
        }
    });
});

Answer №2

To enhance the visibility of the next cell in a table, consider creating a utility function specifically for highlighting. This function can be called on document.ready for each radio button in the table, as well as on the change event of each radio button.

An example implementation could look something like this:

Demo Fiddle: http://jsfiddle.net/abhitalks/tee56wz0/

Demo Snippet:

$("input[type=radio]").each(function() {
    setHighlight(this);  // calling the utility function for each radio on document.ready
});

$("input[type=radio]").on("change", function() {
    setHighlight(this);  // calling the utility function for each radio on change
});

function setHighlight(elem) {
    if (elem.checked) {  
        $("table td").removeClass('highlight');        
        $(elem).parent().next().addClass("highlight"); 
    }
}
td.highlight {background: #33FF99;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr><td><input type="radio" name="common" /></td><td>Cell 2</td><td>Cell 3</td></tr>
    <tr><td><input type="radio" name="common" checked /></td><td>Cell 2</td><td>Cell 3</td></tr>
    <tr><td><input type="radio" name="common" /></td><td>Cell 2</td><td>Cell 3</td></tr>
    <tr><td><input type="radio" name="common" /></td><td>Cell 2</td><td>Cell 3</td></tr>
</table>

Answer №3

$(document).ready(function () {
    var checkedRadio = $('input:radio:checked');

    if (checkedRadio.is(':checked')) {
        $(checkedRadio).parent('td').addClass('highlight');
    }

    $('input:radio').on('change', function () {
        $('#sort td').removeClass('highlight');
        $(this).parent('td').addClass('highlight');
    });
});

example - http://jsfiddle.net/cn073npq/2/

Answer №4

If you need to create a common click event for radio buttons that will add a specific class to the immediate next td/div element, you can use the following jQuery code:

$("input[type=radio]").on("click", function() {
    $("td").removeClass("active");
    $(this).parent().next().addClass("active");
});

For example, if your HTML code looks like this:

<table>
    <tr><td><input type="radio" name="common" /></td><td>Cell 2</td><td>Cell 3</td></tr>
    <tr><td><input type="radio" name="common" checked /></td><td>Cell 2</td><td>Cell 3</td></tr>
    <tr><td><input type="radio" name="common" /></td><td>Cell 2</td><td>Cell 3</td></tr>
    <tr><td><input type="radio" name="common" /></td><td>Cell 2</td><td>Cell 3</td></tr>
</table>

You can then style the added class using CSS:

.active {background: #00FF00;}

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

Tips for revealing a hidden HTML tag

I am currently trying to validate the content within #textd to ensure it is not empty and contains more than 150 characters. If it meets these conditions, I need to transfer the content to another webpage; otherwise, display an error message based on the c ...

Adding multiple text as label and sublabel in a React MUI Tooltip can be achieved by utilizing the appropriate

I'm struggling to incorporate a MaterialUI Tooltip into my React application with two separate text lines. The first line should serve as the main title, while the second line functions as a sublabel. In this screenshot provided, you can see where I ...

Discover the power of uploading images using HTML5 with PHP

Is there a way to retrieve values of uploaded images after clicking on the submit button using $_POST in PHP (with image upload through HTML5)? For an example of HTML5 image upload, you can check out this link You can access the demo at the following lin ...

Issue detected: Click event for Backbone not properly registered

Hey there, I'm new to Backbone.js and having some trouble with a login feature. Despite initiating the view, I can't seem to get the click event to fire during an ajax call for logging in. Any ideas on what I might be doing wrong? I've even ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

Sending jQuery variables to PHP

Is it possible to transfer a jQuery variable to a php file? Let's take a look at the code in my_js.js: function updates() { $.getJSON("php/fetch.php", function(data) { $.each(data.result, function(){ var s_id = this[& ...

Ways to address the issue of "$ is not a function"

Whenever I attempt to upload an image, this error message pops up: $ is not a function The source of the error can be found here: $(document).height(); ...

Mastering the correct application of flex properties within nested flex containers

I'm struggling with utilizing flexbox properly and would like some clarification on how nesting parent and child elements functions. I understand that the child elements inherit the parent's flex properties, but I'm unsure if this inheritan ...

Is there a way to upload files in AngularJS without using AJAX or jQuery?

Currently, I am looking to create a gallery that allows for the uploading of multiple images. While I have come across some options that utilize ajax to immediately send the files, I prefer a solution that involves form submission. In addition, I would li ...

Sorting JSON data using JQuery Ajax

I've encountered an issue with sorting JSON data. Here is the JSON data I'm working with: [ { nom: "TERRES LATINES", numero: "0473343687", image: "http://s604712774.onlinehome.fr/bonapp/api/wp-content/uploads/2016/12 ...

JQuery functions for click and hover are not functioning as expected on a div element

I am having trouble with a div that I have declared. The click event is not working as expected, and I also need to use the :hover event in the css, but it isn't functioning either. What could be causing this issue? <div id="info-button" class="in ...

Refresh a div on an ASP MVC page with a controller action without the need to reload the entire page

In my controller, I have implemented the following action: public ActionResult TestItemLogistic() { ControlViewModel model = new ControlViewModel(); model.itemSelected = "Logistic"; return RedirectToAction("MenuList", model); ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

Assigning a unique identifier to a button that will vary depending on the selected radio input

UPDATED HTML: The circumstances have changed because I am no longer in my office, but the concept remains unchanged. The situation is that on a certain part of a website, users have the option to choose from multiple saved addresses. Each address has a un ...

A guide on organizing dates in a datatable using the dd-MMM-yyyy hh:mm tt format

I have encountered an issue with sorting the date column in my datatable. Here is a screenshot showcasing the problem. Below is the code I am using: <table id="tbl" class="table table-small-font table-bordered table-striped"> <thead> &l ...

Empty observables in Knockout ViewModel binding

As I was cleaning up my model to enhance its clarity, I encountered an issue while refactoring. Initially, I utilized a global variable "results" to store the parsed JSON data from my API. After refactoring, I decided to set the model properties directly. ...

Press on a circle to adjust its size to fit the section or division

Is it possible to make a circle expand and fill the section/div when clicked? I want the circle to fill the screen upon clicking, and then have some text appear in its place. Before posting this, I searched on the web and came across this jsfiddle link. ...

The table is too large for the parent div in which it is placed, causing

Check out this example I have for putting a table in a div and making it fill the div: ex1_jsfiddle table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; height: 100%; table-layout: fixed; } td, th { border: 1px sol ...

What methods can I use to gauge the loading time of an AJAX request and showcase a loading panel?

I am facing an issue with my AJAX request that sometimes deals with a large JSON object. I need to display a loading panel during this process, similar to the one shown in the image below (scaled at 45%): https://i.stack.imgur.com/rw9ft.jpg The problem I ...