What is the best way to toggle between tabs using a checkbox that is checked or unchecked?

I have implemented a checkbox with two sets of tabs that are meant to be displayed or hidden based on the checked state of the checkbox.

Currently, the checkbox switches tabs when checked, but does not switch back when unchecked.

What modifications can I make in the code to ensure the checkbox controls the display of tabs?

UPDATED:https://jsfiddle.net/gtcf3y5d/

HTML:

        <li role="tab">
            <label data-target="#Custom">
                <input id="custom-mark" name="intervaltype" type="checkbox" />
                Custom
            </label>
        </li>

    <!-- Tab panes -->
    <div class="tab-content">

        <div role="tabpanel" class="tab-pane" id="Custom">
            <h3>Custom...</h3>
        </div>

         <div role="tabpanel" class="tab-pane active" id="Types">
            <h3>Regular</h3>
        </div>


    </div>

</div>

CSS:

body {
    padding: 1em;
}

/* Mimic Bootstrap's .nav-tabs>li(.active)>a 
   when using radio buttons instead of links in tab headers */
.nav-tabs>li>label
{
    display: inline-block;
    padding: 1em;
    margin: 0;
    border: 1px solid transparent;
    cursor: pointer;
}
.nav-tabs>li.active>label
{
    cursor: default;
    border-color: #ddd;
    border-bottom-color: white;
}

JS:

$('input[name="intervaltype"]').click(function () {
    //jQuery handles UI toggling correctly when we apply "data-target" attributes and call .tab('show') 
    //on the <li> elements' immediate children, e.g the <label> elements:
    $(this).closest('label').tab('show');
});

Answer №1

This solution addresses your requirements perfectly. Essentially, it just toggles the active class between two elements:

$('input[name="intervaltype"]').click(function () {

    $('#Custom').toggleClass('active');
    $('#Types').toggleClass('active');
});
body {
    padding: 1em;
}

/* Replicating Bootstrap's .nav-tabs>li(.active)>a 
   with radio buttons in tab headers */
.nav-tabs>li>label
{
    display: inline-block;
    padding: 1em;
    margin: 0;
    border: 1px solid transparent;
    cursor: pointer;
}
.nav-tabs>li.active>label
{
    cursor: default;
    border-color: #ddd;
    border-bottom-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" 
rel="stylesheet" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>

<div role="tabpanel">
    
        

        
        <li role="tab">
            <label data-target="#Custom">
                <input id="custom-mark" name="intervaltype" type="checkbox" />
                Custom
            </label>
        </li>
        

               
                
    
    <!-- Tab panes -->
    <div class="tab-content">

        <div role="tabpanel" class="tab-pane" id="Custom">
            <h3>Custom...</h3>
        </div>
        
         <div role="tabpanel" class="tab-pane active" id="Types">
            <h3>Regular</h3>
        </div>
        

    </div>
  
</div>

Answer №2

As mentioned in previous comments, it's important to note that this method is not recommended. However, if you still want to proceed with using the checkbox and bootstrap's tab feature, here is a workaround:

In bootstrap's tab functionality, each element that triggers a specific tab should be visible, clickable, and have either a data-target or href attribute to define which tab to display upon clicking.

To replicate this behavior, I needed to simulate the show/hide functionality of bootstrap tabs and manage which tab to show or hide manually.

This is the adapted code:

$('input[name="intervaltype"]').click(function () {
    tabpanel = $(this).parents('[role=tabpanel]')
    tabpanel.find('.tab-content .tab-pane').removeClass('active');
    if ($(this).is(':checked')) {
    tabpanel.find($(this).data('tab-checked')).addClass('active');
    } else {
    tabpanel.find($(this).data('tab-unchecked')).addClass('active');
    }
});
body {
    padding: 1em;
}

/* Styling to mimic Bootstrap's .nav-tabs>li(.active)>a
   when using radio buttons instead of links in tab headers */
.nav-tabs>li>label
{
    display: inline-block;
    padding: 1em;
    margin: 0;
    border: 1px solid transparent;
    cursor: pointer;
}
.nav-tabs>li.active>label
{
    cursor: default;
    border-color: #ddd;
    border-bottom-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"
rel="stylesheet" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<div role="tabpanel">
  <li role="tab">
    <label>
      <input id="custom-mark" name="intervaltype" type="checkbox" data-tab-checked="#Custom" data-tab-unchecked="#Types" />Custom
    </label>
  </li>
  <!-- Tab panes -->
  <div class="tab-content">
    <div role="tabpanel" class="tab-pane" id="Custom">
      <h3>Custom...</h3>
    </div>
    <div role="tabpanel" class="tab-pane active" id="Types">
      <h3>Regular</h3>
    </div>
  </div>
</div>

I strongly advise against using this approach.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Django: Implementing Subdirectory Structure for Static Files

My static files are organized as follows: /static base.css /core /css style.css /js stuff.js When accessing these files locally using href="/static/core/css/style.css", everything works correctly. However, when deploying live, ...

Equal vertical alignment in the center using flexbox

My flexbox layout is set up as shown in the code snippet below: html { height:100%; width:100%; } body { display:flex; flex-direction:column; align-items:stretch; height:100%; width:100%; margin:0; background-color:grey; } header { b ...

Utilize the power of jQuery accordion to organize and display your table

Is there a way to integrate jQuery UI Accordion with an HTML table so that columns can be collapsible? I have tried various methods but haven't been successful. Currently, this is what I have implemented: $(".col1, .col2").addClass("hidden"); $(".s ...

The div elements are constantly shifting positions when viewed in Internet Explorer

After completing my website and testing it across different browsers, I noticed an issue with IE. The contact div and navigation shift around the page in this browser specifically. Can anyone help me out with some code to fix this problem? Link to live ex ...

Can you explain the functionality of isolate scope in angularjs?

I'm having trouble grasping the concept of scope : {}. Here's a snippet of code I've been working on. Why does it always display "strength" in the console instead of the actual array value? // Code goes here var app = angular.module("super ...

The HTML.php form displays boolean radio button values as 'on'

My html.php page includes three buttons: "Clear Page," "Retrieve," and "Update Details." Upon opening the form, users can input either a value for id="siteId" or id="siteName". By clicking the "Retrieve" button, the remaining details of a stored site are ...

Storing information in a database with multiple entries

Displaying a list of inactive users from a mysqli database in a table format, each user has a row with three drop-down menu options - admin, delete user, and activate user. The table is populated using a prepared statement to fetch data from the database. ...

Intersecting Rays and Positioning Spheres with three.js

I have a scenario where ray intersection is functioning properly with tube geometry. Upon ray intersection, a small red sphere and a tooltip appear next to the cursor. The image below shows the scene without a header: When I include a header using a div e ...

Combinations of Typescript dependent unions

I'm struggling with calling the given union that wraps a function and its argument. Is there a way to call it without having to cast? type Wrapper = { fn: (a: string) => void arg: string } | { fn: (a: number) => void arg: number } let f ...

Personalized cursor image using jQuery.css()

I have designed a .png image that I want to use as a custom cursor for a particular element with the class "next". Here is the code I am using, but it doesn't seem to be working. Is there anything important that I may have overlooked? $('.next& ...

Troubleshooting problem with divs overlapping in Internet Explorer 7

Check out this webpage: http://jsfiddle.net/aJNAw/1/ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta ...

Preventing Vue.js from triggering watch on initial load

I need to implement a feature where a button is initially disabled and only becomes enabled when the input value is changed. To achieve this, I am using a boolean flag that is set to true by default and turns false only when the input changes. The v-model ...

Changing file names when uploading with multer

My attempt to change the file names to file1 and file2 ended up renaming both files as file2. HTML <input type="file" name="file1" file-model = "file1"/> <input type="file" name="file2" file-model ...

Is there a more efficient method for dynamically showcasing iframes embedded with assorted jQuery functionalities?

While this method is functional, I am unsure of the underlying logic and suspect there may be a more efficient way to achieve the same result. The webpage contains an iframe with a dynamic src attribute that changes based on user input. I want to ensure th ...

Learn the ins and outs of utilizing the Ajax jQuery function for passing a string URL and data effectively

Currently, I am working on an ajax jquery function: $.ajax({ url: '/Member/SaveCoordinates/@Model.Id', type: "POST", data: window.image.pinpoints, success: function ...

Adjusting the Height of the Video Jumbotron in Bootstrap

One of my main goals is to create a jumbotron with a video that plays, occupying 100% width and 70% height of the screen. However, I am facing an issue where the video follows the scrolling behavior when I don't want it to. Specifically, as I scroll d ...

Having trouble with VueJS Router-link not redirecting to the correct view?

I am facing an issue with the router link. When I use it in a view, it works perfectly fine as I have a clickable link. However, when I include a router link in a component nested within a view, the router link stops working - all I want is to link to the ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

I would like to exclude the item within my ng-repeat loop using ng-if

I'm attempting to utilize ng-if within ng-repeat in order to create Accordions. Depending on the condition value, I want certain items to be skipped in the ng-repeat. For example, if item.condition is true, then only display the accordion. The code b ...

Maintain the original URL when accessing resources on a proxied webpage

My goal is to host a site named site1 within an existing domain, specifically www.gateway.com. For example, instead of accessing www.site1.com/profile, I want it to be accessible at www.gateway.com/site1/profile. To achieve this setup, I am using an NGIN ...