Search code examples
javascriptbuttonselected

Selecting Only One Button in a Set


I've looked through multiple responses and tutorials, but still seem to having trouble with this. If anyone could help me out, it would be greatly appreciated.

$('.tablink').click(function(e){
    $('.tablink').removeClass('active' );
    $(this).addClass('active');
});

The above is the javascript that I'm trying to use to apply the 'active' class to whichever button is clicked. I've provided the buttons themselves below.

<button class="tablink" onclick="openCity('News', this, '#0c0c0c')" id="defaultOpen">
  <strong>News</strong>                                                                          
</button>

<button class="tablink" onclick="openCity('Story', this, '#0c0c0c')">
  <strong>Events</strong>                                                                           
</button>

<button class="tablink" onclick="openCity('Guides', this, '#0c0c0c')">
  <strong>Guides</strong>                                                                                     
</button>

If you need anything else from, I can add more, but my intention is for the first button (the 'News' button) to have the active class by default until another button is clicked, in which case I want the clicked button to become the active one and all others to lose the active class.

Thank you so much in advance!

Edit: Okay, so this should be working but for whatever reason it isn't. I've provided a link below for further assistance: http://lorecraft.forumotion.com/

In the top left, on the sidebar, it's keeping the first tab as active even when the other tabs are clicked. I've added the javascript code to apply to all pages and designated the first button as active. Still no dice.


Solution

  • The simplest solution here is not to use buttons at all, but instead to use radio buttons (which will be hidden) because they provide the mutual exclusivity and label elements that will be styled to look like buttons.

    No JavaScript needed.

    input[type='radio'][name='buttonGroup'] { display:none; }
    label {
      display:inline-block;
      padding:3px;
      border:1px solid #e0e0e0;
      border-radius:3px;
      background-color:#F0F0F0;
      width:10em;
      text-align:center;
    }
    
    /* Clicking a label will select its corresponding hidden radio button
       We can select that radio buttons sibling label and style it. */
    input[type='radio'][name='buttonGroup']:checked + label { background-color:#a0a0a0; }
    <input type="radio" name="buttonGroup" value="one" id="one"><label for="one">News</label>
    <input type="radio" name="buttonGroup" value="two" id="two"><label for="two">Events</label>
    <input type="radio" name="buttonGroup" value="three" id="three"><label for="three">Guides</label>