Struggles encountered when choosing the initial visible item

I have a set of 3 tabs, each with its own heading and content.

However, I only want to display the tabs that the user selects by checking the corresponding checkboxes. There are 3 checkboxes, one for each tab.

Below is the code snippet:

//Function to hide all siblings except the clicked one
function hideAllChildrenButOne(parentId, toRevealId) {
$('#' + parentId).children().css('display', 'none');
$('#' + toRevealId).css('display', 'block');
}

//Function to show the tab header and content when a checkbox is checked
function showSection(parentId, toRevealId, self) {
var relatedSection = $('#' + toRevealId).attr('data-section');


if(self.is(':checked')){
$('#' + toRevealId).addClass('inline-block');
$('#' + toRevealId).addClass('tab_active');
$('#' + toRevealId).siblings().removeClass('tab_active');
$('#' + relatedSection).siblings().removeClass('active');
$('#' + relatedSection).addClass('block');
$('#' + relatedSection).addClass('active');
}

if ($('#'+self.attr('data-header')).hasClass('tab_active')){
                        var count = $(".tab-header:visible").length;        
 if(self.is(':checked') == false && count > 0){
     $(".tab-header:visible:first").addClass('tab_active');
     $('#'+$(".tab-header:visible:first").attr('data-section')).addClass('active');
    }
}

if(self.is(':checked') == false){
$('#' + toRevealId).removeClass('inline-block');
$('#' + toRevealId).removeClass('tab_active');
$('#' + relatedSection).removeClass('block');
$('#' + relatedSection).removeClass('active');
}
}

$(document).ready(function() {
//On clicking a tab header('Father', 'Mother', 'Brother')
$('.tab-header').click(function(event) {
$(this).addClass('tab_active').siblings().removeClass('tab_active');
    var related_section = $(this).attr('data-section');
    hideAllChildrenButOne('relative_content', related_section);
});


//On changing any checkbox with name=relative[]
$("input[name='relative[]']").change(function() {
    var self = $(this);
    showSection('relative_tabs', self.attr('data-header'), self);
});

});
.relative_container{
    position: relative;
    padding: 45px 15px 15px;
    margin: 0 -15px 15px;
    border-color: #e5e5e5 #eee #eee;
    border-style: solid;
    border-width: 1px 0;
    -webkit-box-shadow: inset 0 3px 6px rgba(0,0,0,.05);
    box-shadow: inset 0 3px 6px rgba(0,0,0,.05);
}
@media (min-width: 768px){
.relative_container {
    margin-right: 0;
    margin-left: 0;
    background-color: #fff;
    border-color: #ddd;
    border-width: 1px;
    border-radius: 4px 4px 0 0;
    -webkit-box-shadow: none;
    box-shadow: none;
}
.relative_tabs{
margin-bottom: 15px;
border-bottom: 1px solid #ddd;
list-style: none;
padding: 7px 0;
.relative_tabs:before{
display: table;
content: " ";
}
.tab-header{
display: none;
margin-bottom: -1px;
}
.tab-header>a{
margin-right: 2px;
    line-height: 1.42857143;
    border: 1px solid transparent;
    border-radius: 4px 4px 0 0;
    padding: 9px 15px;
    text-decoration: none;
    cursor: pointer;
}
.tab-header.tab_active>a{
color: #555;
    cursor: default;
    background-color: #fff;
.relative_content div{
display: none;
}
.relative_content>div.active{
display: block;
}
.tab-content{
display: none;
.hidden{
display: none;
}
.inline-block{
display: inline-block;
}
.block{
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
<label>Father<input type="checkbox" name="relative[]" value="Father" data-header="father-tab"></label>
<label>Mother<input type="checkbox" name="relative[]" value="Mother" data-header="mother-tab"></label>
<label>Guardian<input type="checkbox" name="relative[]" value="Guardian" data-header="guardian-tab"></label>

<div class="relative_container">
<div class="relative_header">
<ul class="relative_tabs" id="relative_tabs">
<li id="father-tab" data-section="Father_info" class="tab-header">
<a>Father</a>
</li> 
<li data-section="Mother_info" class="tab-header" id="mother-tab">
<a>Skin Mother</a>
</li>
<li data-section="Guardian_info" class="tab-header" id="guardian-tab">
<a>Guardian</a>
</li>
</ul>
</div>
<div class="relative_content" id="relative_content">
<div class="tab-content" id="Father_info">Info about Father</div>
<div class="tab-content" id="Mother_info">Info about Mother</div>
<div class="tab-content" id="Guardian_info">Info about Guardian</div>
</div>
</div>
</form>

Here is a fiddle link for testing/editing: https://jsfiddle.net/s83evtrm

Most functionalities work as expected, but there are a couple of scenarios that need fixing:

1- If all 3 checkboxes are checked in sequence (starting from "Father"), then "Father" tab is active. Upon unchecking "Guardian", the "Father" tab should switch to "Mother," but this doesn't happen. The visible element remains "Father" instead of switching to "Mother."

To address this, try moving the third condition before the second one:

if(self.is(':checked') == false){
    $('#' + toRevealId).removeClass('inline-block');
    $('#' + toRevealId).removeClass('tab_active');
    $('#' + relatedSection).removeClass('block');
    $('#' + relatedSection).removeClass('active');
}

Prioritize it over the second conditional statement:

if ($('#'+self.attr('data-header')).hasClass('tab_active')){
    var count = $(".tab-header:visible").length;
     if(self.is(':checked') == false && count > 0){
        $(".tab-header:visible:first").addClass('tab_active');
        $('#'+$(".tab-header:visible:first").attr('data-section')).addClass('active');
    }
}

However, keep in mind that this might cause issues with the previous second condition turned third.

2- When selecting a different checkbox other than "Father," followed by another selection and eventual deselection of "Father," neither of the remaining tabs becomes active.

Note: To mark a tab as active, add the class tab_active to the tab heading ("Father", "Mother", etc.) and active to the content ("Info about Father", "Info about Mother", etc.).

How can these problems be resolved?

Answer №1

One potential solution is to simulate a click on the first selected input if none of the tabs are currently active:

// Custom function to hide all siblings except for one
function hideAllChildrenButOne(parentId, toRevealId) {
  $('#' + parentId).children().css('display', 'none');
  $('#' + toRevealId).css('display', 'block');
}

// Show tab header and content when a checkbox is checked
function showSection(parentId, toRevealId, self) {
  var relatedSection = $('#' + toRevealId).attr('data-section');

  if (self.is(':checked')) {
    $('#' + toRevealId).addClass('inline-block');
    $('#' + toRevealId).addClass('tab_active');
    $('#' + toRevealId).siblings().removeClass('tab_active');
    $('#' + relatedSection).siblings().removeClass('active');
    $('#' + relatedSection).addClass('block');
    $('#' + relatedSection).addClass('active');
  }

  if ($('#'+self.attr('data-header')).hasClass('tab_active')) {
    var count = $('.tab-header:visible').length;
    if (self.is(':checked') == false && count > 0) {
      $('.tab-header:visible:first').addClass('tab_active');
      $('#' + $('.tab-header:visible:first').attr('data-section')).addClass('active');
    }
  }

  if (self.is(':checked') == false) {
    $('#' + toRevealId).removeClass('inline-block');
    $('#' + toRevealId).removeClass('tab_active');
    $('#' + relatedSection).removeClass('block');
    $('#' + relatedSection).removeClass('active');
  }
}

$(document).ready(function() {
  // Clicking on a tab header ('Father', 'Mother', 'Brother')
  $('.tab-header').click(function(event) {
    $(this).addClass('tab_active').siblings().removeClass('tab_active');
    var related_section = $(this).attr('data-section');
    hideAllChildrenButOne('relative_content', related_section);
  });

  // Changing any checkbox with name=relative[]
  $('input[name="relative[]"]').change(function() {
    var self = $(this);
    showSection('relative_tabs', self.attr('data-header'), self);
    // If no tab is active, activate the first one by unchecking and checking it.
    if (!$('.tab_active').length) {
      $('input:checked').first().click().click();
    };
  });
});
.relative_container {
  position: relative;
  padding: 45px 15px 15px;
  margin: 0 -15px 15px;
  border-color: #e5e5e5 #eee #eee;
  border-style: solid;
  border-width: 1px 0;
  -webkit-box-shadow: inset 0 3px 6px rgba(0, 0, 0, .05);
  box-shadow: inset 0 3px 6px rgba(0, 0, 0, .05);
}

@media (min-width: 768px) {
  .relative_container {
    margin-right: 0;
    margin-left: 0;
    background-color: #fff;
    border-color: #ddd;
    border-width: 1px;
    border-radius: 4px 4px 0 0;
    -webkit-box-shadow: none;
    box-shadow: none;
  }
}

.relative_tabs {
  margin-bottom: 15px;
  border-bottom: 1px solid #ddd;
  list-style: none;
  padding: 7px 0;
}

.relative_tabs:before {
  display: table;
  content: " ";
}

.tab-header {
  display: none;
  margin-bottom: -1px;
}

.tab-header > a {
  margin-right: 2px;
  line-height: 1.42857143;
  border: 1px solid transparent;
  border-radius: 4px 4px 0 0;
  padding: 9px 15px;
  text-decoration: none;
  cursor: pointer;
}

.tab-header.tab_active > a {
  color: #555;
  cursor: default;
  background-color: #fff;
  border: 1px solid #ddd;
  border-bottom-color: transparent;
}

.relative_content div {
  display: none;
}

.relative_content > div.active {
  display: block;
}

.tab-content {
  display: none;
}

.hidden {
  display: none;
}

.inline-block {
  display: inline-block;
}

.block {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
  <label>Father<input type="checkbox" name="relative[]" value="Father" data-header="father-tab"></label>
  <label>Mother<input type="checkbox" name="relative[]" value="Mother" data-header="mother-tab"></label>
  <label>Guardian<input type="checkbox" name="relative[]" value="Guardian" data-header="guardian-tab"></label>

  <div class="relative_container">
    <div class="relative_header">
      <ul class="relative_tabs" id="relative_tabs">
        <li id="father-tab" data-section="Father_info" class="tab-header">
          <a>Father</a>
        </li>
        <li data-section="Mother_info" class="tab-header" id="mother-tab">
          <a>Mother</a>
        </li>
        <li data-section="Guardian_info" class="tab-header" id="guardian-tab">
          <a>Guardian</a>
        </li>
      </ul>
    </div>
    <div class="relative_content" id="relative_content">
      <div class="tab-content" id="Father_info">Father Info</div>
      <div class="tab-content" id="Mother_info">Mother Info</div>
      <div class="tab-content" id="Guardian_info">Guardian Info</div>
    </div>
  </div>
</form>

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

Problem with incorporating responsive gifs

I'm new to CSS and I'm trying to incorporate an animated GIF as a smartphone screen using Bootstrap to ensure responsiveness. I've managed to get it working for larger and medium screens, but the issue arises when resizing for smaller displa ...

What is the best way to change the height of cells within a grid layout?

Enhancing the buttons with a touch of depth using box-shadow resulted in an unexpected outcome - the shadows bleeding through the gaps and causing uneven spacing. https://i.sstatic.net/LYssE.png In an attempt to rectify this issue, I decided to tweak the ...

Looking to link a click event to a particular hyperlink?

I have a question about attaching click events to hyperlinks. Here is an example code snippet: $(".notice").click(function() { alert("Hello world!"); }); Below is the HTML for my hyperlink: <a href="http://www.bba-reman.com/catalogue/DetailedProdu ...

Tips for optimizing background images for various screen sizes?

I'm experiencing an issue with my background image where the head is being cut off on larger screens. Is there a way to ensure that the entire picture is always displayed regardless of screen size? The initial property for background-size is set to co ...

Customize scripts dynamically in Next.js based on the current environment during runtime

I need to dynamically insert a script into the <head> of my application, with the src attribute depending on a runtime environment variable from my hosting server (OpenShift). If process.env.ENVIRONMENT === "test", I want to add <script ...

The real-time updates on an Angular 2 website can be seen across multiple devices simultaneously

Just getting started with Angular 2 and ran into an interesting issue. When setting up my website, NPM defaults the server to http://localhost:3000. To test the site on another computer, I tried accessing it using my IP address http://10.x.x.x:3000 and eve ...

Transferring Data from Mod_rewrite to PHP using HTML and JavaScript for the User Interface

My web application has two components: the front end built with HTML, JavaScript/jQuery, and the back end using PHP. In its previous state, it utilized unsightly URLs such as host/app/Page.php?userid=1... definitely not aesthetically pleasing! But with a ...

Transferring data from a text area to a table with AngularJS

Creating a C# MVC App with AngularJS My goal is to populate a table with values entered in a text area using Angular. Here is the process: Users input values into a text area like this: A B C When a user clicks a button, a modal window should open and ...

"Step-by-step guide on creating a popup window for editing a row using ng-grid and AngularJS

I recently started diving into angular-js and I'm really impressed with how cool it is. In my search, I came across http://angular-ui.github.io/ng-grid/, which seems to be a user-friendly tool. However, I'm grappling with figuring out how to disp ...

retrieve the month and year data from the input date

I encountered a situation where I'm working with the following unique HTML code: <input type="date" id="myDate"/> <button type="button" class="btn btn-secondary" id="clickMe">MyButton</ ...

Ways to prevent users from being redirected when they press the back button on a webpage

Similar Question: How can I prevent the back button from working in IE and Firefox? I'm currently working on a single page website (DAM) that requires user authentication to enter. After logging in, if a user clicks the back button, they are dire ...

Sorting table tbody elements created dynamically with JavaScript on an npm webpack application is not possible with jQuery UI

My JS-built table is populated with data from a JSON file fetched after a request. I want to be able to drag and drop these tbodys and update the JSON file accordingly. To handle sorting, I decided to use jquery-ui. While .sortable() works well for drag a ...

AngularJS: Monitoring $locationChangeStart for token verification

I am attempting to check if the next has a token or not, but it is not working and I am getting an error: TypeError: Cannot read property 'next' of undefined Any suggestions? app.js .run(function ($rootScope, $location,$log,User) { ...

Leveraging the power of Bootstrap 4 to place the footer beneath all remaining content on the

I am currently working on a React application that consists of a header, container, and footer. To add animation to the route loading process, I had to apply position: absolute to the container section of the page. Within the container, there is a row wit ...

Encountering issues with implementing router.push in Reactjs

Currently, I am working on ReactJS and utilizing Next.js. My current task involves refreshing the page (using routes), but I encountered an error message stating: Error: No router instance found. You should only use "next/router" inside the client-side of ...

How can I dive into a nested array to access the properties of an object within?

My array, called sportPromise, is structured like this: 0: Array[0] 1: Array[1] 2: Array[2] 3: Array[3] When I run console.log(angular.toJson($scope.sportPromise, 'pretty'));, the output looks like this: [ [], [ { "id": 5932, ...

What is the best way to trigger two functions with an 'onPress' event in React Native?

I am encountering some issues while trying to call two methods on the onPress event in the code below. How can I achieve calling one method for starting chatting and another for changing images during the onPress event? The first method is for initiating ...

Using both Typescript and Javascript, half of the Angular2 application is built

My current project is a large JavaScript application with the majority of code written in vanilla JavaScript for a specific platform at my workplace. I am looking to convert this into a web application that can be accessed through a browser. I believe thi ...

Can a webpage be redirected to another page while passing along the id from the original page?

https://i.sstatic.net/3LhYJ.png I have a page that displays shop names and addresses along with an edit function in views.py: def update_shop(request, id): context = {} # * fetch the object related to passed id obj_shop = get_object_or_404(VideoL ...

Position this menu in the top left corner using HTML and CSS

Is there a way to position the vertical menu completely in the top-left corner without any margin? I've set all margins to 0 but there is still about 2px of space. Any ideas on how to fix this? Thank you in advance! ...