abelvf
abelvf

Reputation: 51

Bootstrap Show and Hide a id with a checkbox

I have a div that I want to show if the user make click in a checkbox (yes) and hide if make click in other checkbox (no)

How can I use javascript, jquery or css code to show and hide the div with id "test" depending on the selection of the user in the checkboxes? (yes or no)

<div class="row" id="test">
        //div that I want to show/hide
</div>


//I have this two checkboxes yes__ no__ 
Yes
<input type="checkbox" name="m_name_no" value="no" id="m_id_no" class="check"/> No </input> 
    </div>

Upvotes: 1

Views: 5497

Answers (2)

ZEE
ZEE

Reputation: 5849

You can use the checked for this and do something like so

input[type=checkbox]:checked + div {diplay: block;}

here is an exmple I made for you :

LIVE DEMO

HTML :

<div style="clear:both;">
<input type="checkbox" id="test1ck"> <div class="lool" >Check and Uncheck Me</label><br>
<input type="checkbox" id="test2ck"> <div class="lool" >Check and uncheck me too!</div></div>

CSS :

.lool {
  display: none;
}


input[type=checkbox]:checked ~ div.lool {
  display:block;
  color: red;
}

of course make sure your are not trying to select a parent element, there is no way to select a parent with CSS only

Upvotes: 4

steveo
steveo

Reputation: 365

The easiest way I'm aware of is to add AngularJS and angular-animate to your project (see below). You can then use simple directives to do what you want, and AngularJS does all the "heavy lifting" for you in JavaScript. This doesn't require any custom javascript or css. I included Bootstrap for some extra styling, but it isn't necessary for what you want.

NOTE: There may be a way to do this with checkboxes, but radio buttons were easier to toggle between. If you wanted to use a single checkbox, checked for "yes" and unchecked for "no", the HTML markup would be even simpler.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Example - example-example92-production</title>
  <link data-require="bootstrap-css@*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.6/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.6/angular-animate.js"></script>
</head>

<body ng-app="ngAnimate">
<div>
  Yes: <input type="radio" id="test1ck" ng-click="yesIsChecked = true" value="y" ng-model="checked">
  <br/>
  No: <input type="radio" id="test2ck" ng-click="yesIsChecked = false" value="n" ng-model="checked">
  <br/>
  <div ng-show="yesIsChecked">
    <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  </div>
</div>
</body>

</html>

Upvotes: 0

Related Questions