How to Toggle Content Visibility with jQuery Based on Radio Button Selection

Introduction: In web development, there are often situations where you need to show or hide content based on user input. One common scenario is using radio buttons to control which section of content is displayed. In this tutorial, I'll walk you through how to achieve this using jQuery, a popular JavaScript library that simplifies tasks like DOM manipulation, event handling, and animation.

Step 1: Setting Up the HTML Structure

Let's start by creating a basic HTML structure with three radio buttons. Each radio button will correspond to a different section of content that we want to show or hide based on the user's selection.

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h2>Select an option:</h2>
    <form>
        <input type="radio" name="options" id="option1" /> Option 1<br>
        <input type="radio" name="options" id="option2" /> Option 2<br>
        <input type="radio" name="options" id="option3" /> Option 3<br>
    </form>
    <div id="result1" style="display:none">
        <p>This is the result for Option 1.</p>
    </div>
    <div id="result2" style="display:none">
        <p>This is the result for Option 2.</p>
    </div>
    <div id="result3" style="display:none">
        <p>This is the result for Option 3.</p>
    </div>
</body>
</html> 

 

Step 2: Adding jQuery to Handle the Click Events

Next, we'll add jQuery to listen for when a user clicks on one of the radio buttons. Depending on which option is selected, the corresponding content will be shown while the others are hidden.

<script type="text/javascript">
$(document).ready(function() {
    // Initially hide all results
    $('#result1').hide();
    $('#result2').hide();
    $('#result3').hide();
    // Add click event listeners to the radio buttons
    $('input[name="options"]').on('click', function() {
        if ($('#option1').is(':checked')) {
            $('#result1').show();
            $('#result2').hide();
            $('#result3').hide();
        } else if ($('#option2').is(':checked')) {
            $('#result1').hide();
            $('#result2').show();
            $('#result3').hide();
        } else if ($('#option3').is(':checked')) {
            $('#result1').hide();
            $('#result2').hide();
            $('#result3').show();
        }
    });
});
</script>

Live Js Fiddle demo

 

Share post
You must be logged in to post a comment
Top