Show element if checkbox is checked in Jquery

Show element if checkbox is checked in Jquery

Posted by Luke Beeno on August 7, 2022

Show element if checkbox is checked in Jquery

Show element if checkbox is checked in Jquery

Posted by Luke Beeno on August 7, 2022

In order to show an element if a checkbox is checked: 

Step 1. Add on click listener to checkbox

Step 2. Check if a checkbox is checked

Step 3. Show element once the checkbox is checked

CSS

#basic-info {
  display: none;
}

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 show element if checkbox is checked</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
  <main>
    <div class="container">
        <div class="col-9 pt-5 mx-auto">
            <input type="checkbox" id="show-div"> Show info</input>
            <p id="basic-info">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque</p>
        </div>
    </div>
  </main>
</body>
</html>

JS

$( "#show-div" ).click(function(){
  if ($("#show-div").is(':checked')) {
    $("#basic-info").show();
  }else{
    $("#basic-info").hide();
  }
})