Menu Close

show and hide div elements based on the selection of radio buttons using jQuery

radio

Let’s see how we can use hide() and show() in jquery by the selection of radio buttons. The below example shows different contents of div elements when we click its corresponding radio buttons.

Example:

<!DOCTYPE html>
<html> 
<head>
    <title>Jquery hide and Show based on the selection of radio buttons</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>  
<body>
    <section>
        <div class="container">
            <label><input type="radio" name="demo" value="1"/> Product 1</label>
            <label><input type="radio" name="demo" value="2"/> Product 2</label>
            <label><input type="radio" name="demo" value="3"/> Product 3</label>
            <div class="pdt-show">
                <div id="show1" class="product"><b>"Product 1"</b> selected.</div>
                <div id="show2" class="product"><b>"Product 2"</b> selected.</div>
                <div id="show3" class="product"><b>"Product 3"</b> selected.</div>
            </div>
            </div>
    </section>    
<script>       
    $(document).ready(function(){
        $('input[type="radio"]').click(function(){
    	   var provalue = $(this).val(); 
            $("div.product").hide();
            $("#show"+provalue).show();
        });
    });
</script>
</body>
</html>

 

Add the below stylesheet to the html file for better responsiveness.

body {
    margin: 50px;
    font-family: Arial, Helvetica, sans-serif;
}
label{padding-left: 20px;}
.product{
	display:none;
    padding:10px;
}  
#show1{
	border:1px solid #000fff;
    background: #f1f1f1;
}
#show2{
	border:1px solid #00FF00;
    background: #f1f1f1;
}
#show3{
	border:1px solid #FF0000;
    background: #f1f1f1;
}
.pdt-show{padding: 30px 20px;} 
Posted in HTML, jQuery

You can also read...