Using Javascript, display an image that was previously hidden with CSS when a radio button is selected

Within a table of 25 rows, each row contains an attribute accompanied by an image (represented by a tick symbol) and five radio buttons for rating the attribute from 1 to 5. Upon clicking one of the radio buttons, the hidden image (tick symbol) should become visible.

Here is the HTML code:


    <table>
        <tr>
            <td width="15px"><img id="1ai" src="../PNG Files/Untitled-3.gif" /></td>
            <td style="text-align: left" >Course Structure and its relevance</td>
            <td width="6%"><input type="radio" name="1a" value="5" id="1a1" /></td>
            <td width="6%"><input type="radio" name="1a" value="4" id="1a2" /></td>
            <td width="6%"><input type="radio" name="1a" value="3" id="1a3" /></td>
            <td width="6%"><input type="radio" name="1a" value="2" id="1a4" /></td>
            <td width="6%"><input type="radio" name="1a" value="1" id="1a5" /></td>
        </tr>
        <tr bgcolor="#FCFFE8">
            <td width="15px"><img id="2ai" src="../PNG Files/Untitled-3.gif" /></td>
            <td style="text-align: left" >Syllabus and its coverage</td>
            <td width="6%"><input type="radio" name="2a" value="5" id="2a1" /></td>
            <td width="6%"><input type="radio" name="2a" value="4" id="2a2" /></td>
            <td width="6%"><input type="radio" name="2a" value="3" id="2a3" /></td>
            <td width="6%"><input type="radio" name="2a" value="2" id="2a4" /></td>
            <td width="6%"><input type="radio" name="2a" value="1" id="2a5" /></td>
        </tr>
    </table>

The images are hidden using CSS. JavaScript will need to determine which radio button is selected in order to reveal the corresponding image.

Answer №1

If you want to achieve this effect, here is one way you can do it:

$("table input[type='radio']").click(function() {
    $(this).closest("tr").find("img").show();
});

When a radio button is clicked, this script will locate the parent row of that specific radio button and display the image within that row. Please note that this assumes the image is initially hidden using CSS display: none.

To ensure easier maintenance in the long run, consider the following suggestions:

  1. Assign an ID to the table to target only the intended table with this code, rather than all tables on the page.
  2. Add a unique class name to the image you wish to reveal, so there's no confusion with any potential future images added to the table.

After implementing these improvements, your code could be refined as follows:

$("#choices input[type='radio']").click(function() {
    $(this).closest("tr").find(".tick").show();
});

In the scenario where you need to achieve this functionality using plain JavaScript without relying on a selector engine, a different approach would be necessary by building the image ID dynamically. Provided the table has been assigned the "choices" ID, the process might look like this:

// cross-browser event binding
function addEvent(elem, evt, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(evt, fn, false);
    } else {
        elem.attachEvent("on" + evt, function() {
            return(fn.call(elem, window.event));   
        });
    }
}

addEvent(document.getElementById("choices"), "click", function(e) {
    var target = e.target || e.srcElement;
    if (target.tagName == "INPUT" && target.type == "radio") {
        var name = target.name;
        document.getElementById(name + "i").style.display = "inline";
        console.log("displaying image " + name + "i");
    }    
});

Check out a demo illustrating this technique: http://jsfiddle.net/jfriend00/uMUem/

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

Utilizing jQuery to display an element once JSON data is returned to the page

When a user clicks on an image on page 1, they trigger a pop-up window that allows them to upload an image file. The PHP script responsible for handling this action will return a JSON-encoded string containing a variable named 'id'. Here is an e ...

Implementing asynchronous file reading with module.exports in Node.js

Apologies in advance for what may seem like a basic question, but I'm delving into the inner workings of node and need help with a particular issue: I am trying to send an object or file from fs.readFile using require and module.exports. So far, this ...

What's the secret behind generating a crisp 400 on paper?

Understanding Why it Prints 400 I'm struggling to comprehend the logic behind this var x = {}, y = { key: "y" }, z = { key: "z" }; x[y] = 100; x[z] = 200; console.log(x[y] + x[z]); ...

Trigger a JavaScript function just before navigating to the next page in the background

I am trying to call a Javascript function from the code-behind in vb.net, but I'm facing an issue where the function is not being executed properly due to redirection to the next page before it runs. I do not want to trigger this function on an Onclic ...

Modify the paragraph content upon clicking

After experimenting with JavaScript to switch images, I now want to explore how to do the same with text. My dilemma lies in having 10 different paragraphs (where each link corresponds to a specific paragraph), but I'm unsure of where to input these ...

View content from a text file on a webpage

Hi everyone, I could really use some assistance with a project I'm currently working on. As someone who is new to programming, I am facing a challenge. My goal is to showcase the contents of a plain text file on a webpage. This text file, titled titl ...

two adjacent elements filling the entire height of the window at 100% dimensions

Is there a way to place two elements side by side, with one of them (the textarea) always being 100% height of the window? I've looked at similar questions here but can't figure out how to make it work. Can you help me with this? html: <div ...

Is it possible for me to create a list in alphabetical order beginning with the letter B instead of A

My task involves creating a summary of locations using the Google Maps API. The map displays letters corresponding to different waypoints, and I have a separate <div> containing all the route information. Currently, I have the route information stru ...

I need to obtain the URL pathname on a server component in Next.js version 13 - how is this achieved

I'm facing an issue with retrieving the pathname of a server component located in the app directory. Despite attempting to obtain it through window.location, I haven't been successful. Is there an alternative method I can use to achieve this? ...

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...

Conceal a div element only if it is nested within a particular div class

I have a question about hiding a specific div within another div. Here is the scenario: <div class="xp-row xp-first-row"> <div class="social-buttons"> Some Content Here </div> </div> The goal is to hi ...

Encountering a login issue with the jsonwebtoken code, specifically getting the error message "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')."

I encountered an error in my console saying, "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')." I am seeking assistance in resolving this issue. Below is the code snippet: import { mAdmin } from &q ...

Is there a method to determine if localForage/indexedDb is currently handling data operations?

Currently, I am working on a webapp that utilizes async localForage (specifically angular localForage). My goal is to alert users if they attempt to close the browser window while there are ongoing localForage operations. I have observed that some browser ...

Need to ensure that an AJAX form doesn't resubmit without the need for a page

Encountering a peculiar mystery issue here... I have created a button on a webpage that triggers a form submission. The form is enclosed within a DIV, which dynamically updates to display the modified data. (this is embedded in a smarty template) form: ...

Ways to transfer variables between JavaScript files using a deferred function

I am encountering an issue while trying to retrieve a json object from another JS file. It appears to be a timing problem as the setTimeout function I added runs twice; first with the object correctly populated, and then again with the object becoming unde ...

Find and replace string words containing special characters such as $ or !

Looking to process an input string in a specific way - // Input string - 'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$' // Processed string 'My pen cost is <penCost> manufactured ...

Can you create different width sizes using two types in HTML?

As I delve into learning HTML, I find myself curious about the possibility of combining multiple size types for width. For instance, is it possible to set a width that is both 10px and 3vw? While I understand that this isn't directly supported, I wond ...

Is it possible to use Node.js without resorting to template engines

Recently, I embarked on a journey to explore the world of backend development, focusing my attention on Node.js. As I delved into Express.js and familiarized myself with routing, a curious thought crossed my mind. Is there a method to transmit data direc ...

Is there a way to preserve all the downloaded node modules in the package.json file?

Is there a way to keep track of all the node modules installed in package.json without the need for reinstalling them? I've heard about running npm init --yes, but I'm not entirely convinced if that will do the trick. Any assistance on this mat ...

Node receiving empty array as result after processing post request

My current task involves testing the post method on Postman. Strangely, every time I post the result it shows an empty array []. Upon further investigation by console logging on the node side, it also returns an empty array. CREATE TABLE users ( user_ ...