Tri-party class switch-up

I successfully implemented two radio buttons to toggle between alternative texts:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
            type="text/javascript"></script>
    <style type="text/css">
        .displayNone { display: none; }
    </style>
</head>

<body>

    <input type="radio" name="toggle" />A
    <input type="radio" name="toggle" />B

    <span class="A">A</span>
    <span class="B displayNone">B</span>

<script type="text/javascript">
    $('input[name=toggle]').change(function() {
        $('.A, .B').toggleClass('displayNone');
    })
</script>

</body>
</html>

Now, I am looking to expand this functionality with three radio buttons to switch between three different texts:

<input type="radio" name="toggle" />A
<input type="radio" name="toggle" />B
<input type="radio" name="toggle" />C

<span class="A">A</span>
<span class="B displayNone">B</span>
<span class="C displayNone">C</span>

I believe the solution I have in mind might be too lengthy. Can you suggest a more concise approach?

Answer №1

Here's another method to achieve the same result:

$('input:radio[name="toggle"]').change(
    function(){
        $('span')
            .eq($(this).index())
            .removeClass('displayNone')
            .siblings('span')
            .addClass('displayNone');
    });​

Check out this JS Fiddle demo for a live example..


Edited to include a pure CSS alternative, suitable for modern web browsers:

input[type=radio]:nth-child(1):checked ~ span:nth-of-type(1),
input[type=radio]:nth-child(2):checked ~ span:nth-of-type(2),
input[type=radio]:nth-child(3):checked ~ span:nth-of-type(3){
    height: 1em;
    width: 100%;
    background-color: #f90;
    -webkit-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -o-transition: all 1s linear;
    -moz-transition: all 1s linear;
    transition: all 1s linear;
}

span {
    display: block;
    overflow: hidden;
    height: 0;
    width: 0;
    background-color: #fff;
    -webkit-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -o-transition: all 1s linear;
    -moz-transition: all 1s linear;
    transition: all 1s linear;
}​

View the CSS-only JS Fiddle demo here..

Resources for jQuery methods:

CSS Resources:

Answer №2

Here is a simple approach: Check out this jsFiddle example.

$('input[name=toggle]').change(function() {
    $('span').addClass('displayNone').filter('span:eq(' + $(this).index() + ')').removeClass('displayNone');
})​

Answer №3

If you're looking for a creative way to hide and show elements, this CSS trick might do the trick. Check it out:

div {
  visibility: hidden;
}

input[type="checkbox"]:checked + * {
  visibility: visible;
}

Try it out and see how it works for your project!

Answer №4

Here is an alternative method to achieve the same result (see demonstration: http://example.com)

<input type="radio" name="switch" value="X" checked="true"/>X
<input type="radio" name="switch" value="Y"/>Y
<input type="radio" name="switch" value="Z"/>Z

<br />
<span id="X" class="contentHidden">X</span>
<span id="Y" class="contentVisible displayNone">Y</span>
<span id="Z" class="contentVisible displayNone">Z</span>

$('input[name=switch]').change(function() {
    var selectedVal = this.value;
    $(".contentVisible").each(function() {
        $(this).toggleClass('displayNone', this.id != selectedVal);
    });                                                    
});

The key point to note here is that you can utilize the second parameter in .toggleClass() to determine whether the class should be added or removed.

Answer №5

Assign a common class to all text spans, but give each one a unique ID:

<span class="text-span" id="span_1">Text 1</span>
<span class="text-span hidden" id="span_2">Text 2</span>
<span class="text-span hidden" id="span_3">Text 3</span>

Hide all the text spans initially and then display the desired one:

function showText(id) {
    $(".text-span").hide();
    $("#" + id).show();
}

Update:

To prevent flickering, you can also utilize jQuery's not selector:

$(".text-span").not("#" + id).hide();
$("#" + id).show();

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

Express always correlates the HTTP path with the most recently configured route

Recently, I encountered a strange issue with my Express routes configuration. It seems that no matter which path I request from the server, only the callback for the "/admin" route is being invoked. To shed some light on how routes are set up in my main N ...

Creating a dropdown menu using jQuery

I have a situation where I am linking a dropdown menu to the "onChange" event of a textbox. The functionality works as expected, however, when I click the button associated with it, the click event is not triggered. Below is the script being used: <sc ...

What could be causing Prettier code formatter to suddenly stop formatting in VS Code?

I've been having trouble formatting my code using Prettier in VS Code. Even after reinstalling it, the issue persists and I can't seem to format my HTML/CSS code properly. The screenshot I provided shows that the code remains unformatted even aft ...

Unlocking the Secrets of JSON Data Retrieval

Could someone assist me in extracting data from the json provided below? I have received a json data in the following format, where each record contains "{0}". My query is how can I retrieve data from this format or if there is a way to remove "{0}" from ...

Python and JavaScript fundamental interaction

My current setup involves having a local HTML page named leaflet.html, which is being shown in an embedded browser within a python-tkinter application. Within the leaflet.html file, there exists a straightforward JavaScript code snippet that includes a fu ...

The player remains unchanged

Hi, I am currently working on my app to update a player's age. To start off, I have added three players: const playerOne = store.dispatch(addPlayer({ firstName: 'Theo', lastName: 'Tziomakas', position: 'Goakeeper ...

Please enter a string and I will locate it within an array. If found, I will provide you with information about that string as a fact

I have a specific challenge I need help with. I have a pre-defined array that contains country names and corresponding facts about each country. What I am trying to achieve is to check if the user-inputted word matches any of the countries in my array, a ...

React hooks causing dynamic object to be erroneously converted into NaN values

My database retrieves data from a time series, indicating the milliseconds an object spends in various states within an hour. The format of the data is as follows: { id: mejfa24191@$kr, timestamp: 2023-07-25T12:51:24.000Z, // This field is dynamic ...

identifies a data point from a combined dropdown menu

Is there a way to detect a specific value from a multiplied combo box? For example, when the value in one of the combo boxes changes to "2", a component is displayed. However, if the value in another combo box changes to anything other than "2", the compon ...

The provider for authentication, which is linked to the AuthenticationService and subsequently to the loginControl, is currently unidentified

Attempting to implement an authentication service in my application, I encountered an error when trying to call it within my controller: !JavaScript ERROR: [$injector:unpr] Unknown provider: AuthenticationServiceProvider <- AuthenticationService <- ...

What is the best way to remove <a> tags from an XML document?

I'm dealing with <a> tags within an XML file and I need to remove only the <a> tags. For instance: <test>This is a line with <a name="idp173968"></a> tags in it</test> I am unable to use str_replace to replace t ...

Clicking on the icon reveals the current date

I need some help with the input field that displays the calendar date. Currently, I can only click on the input field to show the calendar date. What I actually want is for users to be able to click on a calendar icon to display the calendar date, which sh ...

`Monitoring and adjusting page view during window resizing in a dynamic website`

Situation: Imagine we are reading content on a responsive page and decide to resize the browser window. As the window narrows, the content above extends down, making the entire page longer. This results in whatever content we were previously viewing bein ...

Using Double Equal in a JavaScript For Loop

I'm struggling to comprehend why utilizing a double equals (or even a triple equals) in the condition of a for loop doesn't function as expected. Consider this example: for (i = 1; i == 5; i++){ console.log(i) } When I replace == with <= ...

Working with color fills in Three.js shapes

Looking for some help with code that generates a yellow circle: let radius = 5, segments = 64, material = new THREE.LineBasicMaterial( { color: 0xF0C400 } ), geometry = new THREE.CircleGeometry( radius, segments ); geometry.vertices.shift ...

How can you ensure seamless synchronization while logging in a user with ReactJS and retrieving data from the API?

Is there a way to synchronize and run these two functions in succession before calling console.log(user) and setLogin()? The goal is to ensure that all the information retrieved from the API is available in the user context before activating the setLogin() ...

Is it necessary to bring in CSS for the following page?

Should CSS be imported and used across multiple pages in a web application? Is the page structure outlined below considered acceptable, or is there a standard practice to follow? /pages /home index.js index.module.css /cart ...

I attempted to upload an image using the Google Drive API, but encountered an error in the response

I am attempting to upload an image using the Google Drive API, but I encountered an error in the response message. The error reads as follows: "Failed to load resource: the server responded with a status of 403 ()" ...

Utilizing the $scope variable within an event in the Google Maps API

I am having an issue using $scope within this function. Where should I define the argument $scope so that it works properly? Thank you Below is the basic structure of my code with key lines included: myApp.controller('myCtrl', ['$scope&ap ...

What is the implication when Typescript indicates that there is no overlap between the types 'a' and 'b'?

let choice = Math.random() < 0.5 ? "a" : "b"; if (choice !== "a") { // ... } else if (choice === "b") { This situation will always be false because the values 'a' and 'b' are completely disti ...