Modify the paragraph's class upon clicking the radio button

I have been struggling with changing the color of <p> based on the radio button selected using two classes, red and blue. However, for some reason, it's not working as expected.

If anyone has any insights or suggestions on how to fix this issue, I would greatly appreciate it.

<html>
<head>
<script type="text/javascript">

var element = document.getElementsByName('color');

if (element[0].checked) {
    $("p").toggleClass("blue");
} else {
    $("p").toggleClass("red");
}

</script>

<style type="text/css">

.blue {
    color: blue;
}
.red {
    color: red;  
}
</style>

</head>

<body>

<input type="radio" name="color" value="blue">blue<br>
<input type="radio" name="color" value="red">red

<p>When a user clicks on a radio-button, it becomes checked, and all other radio-buttons with equal name become unchecked.</p>

</body>
</html>

Answer №1

It's important to note that when writing JavaScript, it will run before your elements are even in the DOM. To ensure proper execution, place your JavaScript code at the end of the body or use an event handler triggered upon document load.

Here is the HTML code snippet :

<input type="radio" name="color" value="blue">blue<br>
<input type="radio" name="color" value="red">red
<p id="myParagraph">When a user clicks on a radio-button, it becomes checked, and all other radio-buttons with equal name become unchecked.</p>

In Vanilla JS :

document.addEventListener('DOMContentLoaded', function() {

   var radioButtons = document.getElementsByName('color');
   var paragraph = document.getElementById('myParagraph');

    for(var i=0;i< radioButtons.length;i++)
    {
        var elem = radioButtons[i];
        elem.addEventListener('change',function(e){     
            console.log(paragraph);
            if(paragraph.className)
                paragraph.className = this.value;
            else
                paragraph.classList.add(this.value);
        }
        ,false);

    }
});

Check out this fiddle

If you prefer using jQuery (and have included it correctly on your page), you can do so like this:

$('document').ready(function() {

    $('input:radio').on('change',function(){
        $('#myParagraph').addClass(this.value);
    });

});

View the jQuery implementation here

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

Center-align the table element

I've been struggling to center align this table element, specifically the one containing the square, but nothing seems to be working. Can anyone lend a hand in fixing this issue? <table> <tbody> <tr> <td>TURKEY - SU ...

What are the steps to turn off response data compression in an Express server?

How can I receive the 'Content-Length' response from the server without gzip compression enabled? I am using a compression middleware for this purpose: const shouldCompress = (req, res) => { if(req.headers['x-no-comprassion']) { ...

I would greatly appreciate any recommendations on how to troubleshoot and

I've been working on the "Map the Debris" challenge at freecodecamp, and I'm facing an issue. While my code works fine in my PC's editor, it doesn't satisfy the conditions when I paste it into the website area. Any suggestions on how t ...

Employing PHP conditions alongside JavaScript to conceal the div elements

I have been struggling with a problem for the past few hours and still haven't found a solution. I am new to php. What I am trying to achieve is to display and hide a div based on a PHP condition. Here is the scenario: Please note: By default, the DI ...

Form submission is not functioning as expected

I am having trouble with my form submission. When I try to submit the form, nothing happens. I have tried various solutions but have not been able to resolve the issue. I have reviewed all available resources but still cannot figure out why my code is not ...

Troubleshooting problems with a JavaScript game that involves guessing numbers

I have been given a challenging Javascript assignment that involves using loops to create a counting betting game. The concept is simple: the User inputs a number, and the computer randomly selects a number between 1 and 10. The User can then bet up to 10 ...

Tips for incorporating a dynamic basePath into your NextJS project

For my new app, I am trying to include the groupID in the URL before the actual path, such as 'https://web-site.com/1/tasks'. The NextJs docs mention a basePath that is set at build time and cannot be modified. With numerous routes in my current ...

Is there a way to merge these arrays into a single array?

With the current code I am obtaining numerous JSON objects within separate arrays: Here is the code snippet: for (let i=1; i<=150;i++){ fetch(`A valid URL ${i}`) .then(result => result.json()) .then(result => console.log(result.data.results)) ...

Is there a way to efficiently manage multiple modules in AngularJS? I've put in a lot of effort, but while one module is functioning properly, the

angular .module('ApplicationOne',[]) .controller('myControllerOne', function($scope){ $scope.name = "Luther"; $scope.fname = "Martin"; $scope.ed = "B.TECH"; }); angular .module('App2&apos ...

What is the best way to ensure the div stays in sync with scrolling?

Trying to synchronize two divs while scrolling. Essentially, I have a page scroll and want to fix the second div when it reaches the top. Please refer to the gif icon attached for clarification. You can view my progress so far here. The current issue in ...

Retrieve information using an AJAX call

There is JSON data stored in a file that I need to read. The correct file data is printed to the console.log. What steps should I take to assign this data to variable x? Currently, when I execute the code, x ends up being undefined. function getData() { ...

Is it possible to list bash/sh files as dependencies in package.json?

Currently, I have a bash script named publish.sh that I use for publishing modules to npm. Since I am constantly adjusting this script, I find myself needing to update every copy of it in each npm module I manage. Is there a method to include this bash sc ...

Anchoring links on a webpage that provide users with a clear indication of their current position within the page

In the scenario of a single-page website with various sections (divs) and a header containing links to different anchors on the page, there is a desire to have an indicator highlight which anchor the user is currently viewing. An example of this can be s ...

Achieving Content Centering in React Material UI: A Guide to Aligning to the Middle of the Page

Currently, the button is displaying in the top left corner. How can I move the button to the center of the page? import {Button} from '@mui/material'; function App() { return ( <Button variant="contained">Hello World</ ...

A guide to resetting items directly from a dropdown select menu

I need help with clearing or resetting select options directly from the dropdown itself, without relying on an external button or the allowClear feature. Imagine if clicking a trash icon in the select option could reset all values: https://i.stack.imgur. ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

Change the date string to year, month, and day

When using Ajax's getResponseHeader("Last-Modified"), it returns a date string with the format displayed below: Thu Oct 13 2016 13:05:17 GMT+0200 (Paris, Madrid, sommartid) I am wondering if it is achievable in javascript to extract the year, month, ...

Whoops! The input buffer seems to be containing an image format that is not supported while attempting to utilize Next JS next-opt

I initially used the default Image Optimization component in my Next JS app, only to realize that the site could only be hosted on Vercel and not on other web hosting platforms. This limitation prompted me to explore the next-optimized-images package, whic ...

The React JSX error message "Maximum update depth exceeded" occurs when there

It appears that I am facing an issue of creating an infinite loop while passing props from one class to another. Despite ensuring that the buttons are correctly bound and trigger only once, the problem persists without any solution in sight after thorough ...

Can local caching in ALL MAJOR browsers (Safari/Firefox/Opera/Chrome/IE) be achieved by an HTML5 web app that bypasses browser permissions?

Exploring the capabilities of the HTML5 offline application cache, I conducted boundary tests to observe how different browsers handle edge cases. Particularly, I focused on understanding the cache quota. To investigate further, I created and served an of ...