简体   繁体   中英

How to only allow "checking" of only one checkbox

How can I edit this codepen to allow for only checking one item, and if another item is checked, the previous one is unchecked and to use a custom image for the check instead of the current check automatically generated?

Codepen: https://codepen.io/claviska/pen/aLxQgv

<!-- Example Dropdown -->
<div class="dropdown">
  <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown">Menu</button>
  <div class="dropdown-menu">
    <a href="#" class="dropdown-item">Item 1</a>
    <a href="#" class="dropdown-item dropdown-item-checked">Item 2</a>
    <a href="#" class="dropdown-item">Item 3</a>
  </div>
</div>

<p class="mt-4">
  <a href="https://www.abeautifulsite.net/adding-a-checked-state-to-bootstrap-4-dropdown-menus">View the original post</a>
</p>

<p>
  This code is by <a href="https://twitter.com/claviska">@claviska</a> and has been released into the public domain.
</p>

.dropdown-item-checked::before {
  position: absolute;
  left: .4rem;
  content: '✓';
  font-weight: 600;
}

body {
  padding: 1rem;
}

// Toggle checkmarks
$(document).on('click', '.dropdown-item', function(event) {
  event.preventDefault();
  $(this).toggleClass('dropdown-item-checked');  
});

Desired result:

在此处输入图片说明

Notice only the selected one shows an icon to the left of it.

I don't see why hidding radio button would be a problem (I don't mean for accessibility, I only mean for what you want to achieve).

Is that what you want?

 [name=items] { display: none; } label { display: block; padding-left: 1rem; } :checked + label::before { position: absolute; left: .4rem; content: '✓'; font-weight: 600; }
 <input type="radio" name="items" id="item-1"> <label for="item-1">Item 1</label> <input type="radio" name="items" id="item-2" checked> <label for="item-2">Item 2</label> <input type="radio" name="items" id="item-3"> <label for="item-3">Item 3</label>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM