Zwo
Zwo

Reputation: 1113

Checkbox in bootstrap label not working

I was trying to follow this tutorial to have checkboxes displayed as buttons for my angular app, but something wasn't working for me, the checkbox value does not change, and the onclick function is not called :

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-primary">
            <input type="checkbox" onclick="alert('is not shown')"> Click me <!-- Here -->
        </label>
    </div>
</body>
</html>

But if I remove the boostrap.js script (or the class="btn btn-primary") it works :

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-primary">
            <input type="checkbox" onclick="alert('is shown !')"> Click me 
        </label>
    </div>
</body>
</html>

How do I make this working without removing the bootstrap.js script?

Upvotes: 0

Views: 1915

Answers (2)

Pugazh
Pugazh

Reputation: 9561

Just use onchange. Checkbox onchange should be more meaningful than onclick.

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary">
      <input type="checkbox" onchange="alert($(this).is(':checked'))">Click me
    </label>
  </div>
</body>

</html>

Upvotes: 1

Lalji Tadhani
Lalji Tadhani

Reputation: 14159

Add custom css for input

.btn-group input[type=checkbox]{
    clip: initial !important;
    cursor: pointer;
    height: 29px;
    left: 0;
    opacity: 0;
    pointer-events: initial !important;
    top: 0;
    width: 100%;
}

https://jsfiddle.net/xt3b88z2/

Upvotes: 4

Related Questions