JQuery Toggle only 1 item and the others not clicked

Matt Elhotiby picture Matt Elhotiby · Jul 18, 2010 · Viewed 9.8k times · Source

Ok so i have this Jquery that will toggle some radio buttons on the page. I want it so when someone clicks on one of the radio buttons the others are not clicked. Currently the way i have it they can select 3 at a time and I need it to act like a regular radio button that one is clicked and the others are not

jQuery:

$(function () {
  $('.box-ul .btn .dot').click(function () {
    $(this).toggleClass('clicked');
  });
});

HTML:

<div class="box-ul box-video right">
    <ul>
        <li><span class="yes"></span><p>Easy to Use</p></li>
        <li><span class="yes"></span><p>Step by Step<br /><span>details instructions</span></p></li>
        <li><span class="yes"></span><p>Setup time<br /><span>under 30 mins</span></p></li>
        <li class="btn btn-expanded">
          <div class="btn-t">
            <span class="dot left"></span>
          <p class="left">Expanded<br />
            <span>This is the extend button It has space for slightly more info.</span>
          </p>
            <div class="cl">&nbsp;</div>
          </div>
        </li>
        <li class="btn">
          <div class="btn-t">
            <span class="dot left"></span>
            <p class="left">Green Doggies</p>
            <div class="cl">&nbsp;</div>
          </div>
          </li>
        <li class="btn">
          <div class="btn-t">
            <span class="dot left"></span>
            <p class="left">Email Support</p>
            <div class="cl">&nbsp;</div>
          </div>
        </li>
    </ul>
</div>

Answer

Nick Craver picture Nick Craver · Jul 18, 2010

Use .removeClass() class on all the matching elements that aren't the one you clicked on first, like this:

$('.box-ul .btn .dot').click(function () {
  $('.box-ul .btn .dot').not(this).removeClass('clicked');    
  $(this).toggleClass('clicked');
});​

You can test it here. In this case we're selecting all the other matching '.box-ul .btn .dot' elements, filtering out the one we clicked on with .not(), and doing a .removeClass() on them. The last part is still a .toggleClass() so you can de-select via clicking on the active one as well. If you don't want to be able to de-select (even more like a radio button) then just change that to .addClass().