user38250 user38250 - 5 months ago 22
Javascript Question

display an image only when at least one of a specific group of radio buttons is selected

I have some radio buttons. Let's name them
A1 B1 A2 B2 C2 A3 B3 A4 C4

I want an image to be only displayed when at least one of the B radio buttons is selected.

test cases:

B1 B2 clicked - display image

A1 A2 B3 clicked - display image

A1 A3 clicked - don't display image

What I have tried?

I am trying to keep a count of radio buttons clicked belonging to radio button group B and displaying image when that count is greater than 1.

I am new to jquery and this solution looks dirty to me.

Is there any other good solution?

I forgot to mention there can be unknown number of B radio buttons on a page


A regular check will suffice. Try something along these lines:


    B1 = document.getElementById("B1"),
    B2 = document.getElementById("B2"),
    img = document.getElementById("image-id"),
    rad = document.getElementByClassName("radiobuttons-class"); // Class of all the buttons

for (var i = 0; i < rad.length; i++) {
    rad[i].onchange = function() {
        if (B1.checked || B2.checked) {
   = "inline-block"; // Or whatever you want it to be
        else {
   = "none";

The if/else check can also be written shorter as: = (B1.checked || B2.checked) ? "inline-block" : "none";


$(".radiobuttons-class").on("change", function() {
    if($("#B1").attr(checked) || $("#B2").attr(checked)) {
        $("#image-id").css("display", "inline-block");
    else {
        $("#image-id").css("display", "none");