JQuery Toggle only 1 item and the others not clicked
Asked Answered
G

2

5

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>
Gca answered 18/7, 2010 at 20:49 Comment(0)
C
10

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().

Contrast answered 18/7, 2010 at 20:53 Comment(1)
@Matt - Welcome :) edited your question a bit...just for future reference, if you separate the JavaScript and HTML into different code blocks, you'll get better code highlighting on both :)Contrast
L
0

Instead of a blanket .removeClass() on everything, I would do:

$(this).closest('.box-ul').find('.btn .dot').not(this).removeClass('clicked');

This only deselects ones within the clicked radio button's .box-ul.

Laodicean answered 18/7, 2010 at 20:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.