javascript - Using bootstrap button to toggle bold state -


bootstrap toggle button should used toggle div text bold state.

on first click button should remain in checked state , text become bold. on second click button should remain in unchecked state , text should become normal. tried code below first click worked. second click not remove bold text.

how fix ?

<head>      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">        <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">      <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>      <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>        <script>          $(function () {              $('#designer-javascript-bold').change(function (e) {                  //         $(this).button('toggle');                  var checked = $(this).val();                  $(".ui-selected").each(function () {                      $(this).css("font-weight", checked === "on" ? "bold" : "normal");                  });              });          });        </script>    </head>  <body>      <div class="btn-group" data-toggle="buttons">          <label class="btn btn-info">              <input type="checkbox" autocomplete="off" id="designer-javascript-bold"><span class="glyphicon glyphicon-bold"></span>          </label>      </div>      <div class="ui-selected">toggleable text</div>  </body>

i'm not sure why checking value of input. checked property seems more relevant:

var checked = $(this).prop('checked'); 

this give boolean value use in ternary:

$(this).css("font-weight", checked ? "bold" : "normal"); 

example:

<head>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">      <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>    <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>      <script>      $(function() {        $('#designer-javascript-bold').change(function(e) {          var checked = $(this).prop('checked');          $(".ui-selected").each(function() {            $(this).css("font-weight", checked ? "bold" : "normal");          });        });      });    </script>    </head>    <body>    <div class="btn-group" data-toggle="buttons">      <label class="btn btn-info">        <input type="checkbox" autocomplete="off" id="designer-javascript-bold"><span class="glyphicon glyphicon-bold"></span>      </label>    </div>    <div class="ui-selected">toggleable text</div>  </body>


Comments