1

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?

<!-- 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');  
});
  • 4
    are you looking for radiobutton? – Sfili_81 Nov 15 '21 at 15:42
  • 8
    Don't use checkboxes for this - you will kill UX and accessibility this way. This is exactly the intended function of `` – esqew Nov 15 '21 at 15:44
  • [Does this help?](https://stackoverflow.com/questions/32929472/making-a-drop-down-menu-containing-radio-buttons) –  Nov 15 '21 at 15:47
  • Yeah, should be radio if you want to convey users that only `one of` can be selected/chosen at any point in time. – Zameer Haque Nov 15 '21 at 15:48
  • @rocket129083 you can do it with css –  Nov 15 '21 at 15:55
  • Basic CSS `[type="radio"]:checked + label::before{}` – epascarello Nov 15 '21 at 15:55
  • Please keep in mind that showing an SVG of a checkmark still presents the UX issue that @esqew mentioned. We conditioned people to associate checkmarks with independent on/off choices. – timotgl Nov 15 '21 at 15:57
  • @rocket129083 oh gotcha, you can maybe put with some js that the radio button is hidden, but i cant help you, sorry, i am more of a html, css guy, than js :) –  Nov 15 '21 at 16:02
  • Good luck tho :) –  Nov 15 '21 at 16:02

1 Answers1

1

I don't see why hiding 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>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Cedric Cholley
  • 1,956
  • 2
  • 9
  • 15