Creating HTML tabs using jQuery with input[type="radio"] tutorial for beginners

I'm having trouble creating a tab with input[type="radio"] using Jquery. The tab works fine on the first click, but it doesn't work on the second click. I can't figure out where the issue is in the Jquery code. Can someone assist me?

To view the code, follow this link: Click here

$('.tablist').on('click', 'input', function(){

  var tabList = $('.tablist-content').attr('id');
  if($(this).attr('type','radio').is(':checked') || $(this).next('label').text() == tabList){
    $(this).parents('.tabWrapper').find("#" + tabList).show();
    console.log(tabList);
  }
  else {
    $(tabList).hide();
  }

});
.tablist-content {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tabWrapper">
<ul class="list-unstyled tablist">
  <li>
    <input type="radio" name="tablist" id="tablist1">
    <label for="tablist1">List1</label>
  </li>
  <li>
  <input type="radio" name="tablist" id="tablist2">
    <label for="tablist2">List2</label>
  </li>
</ul>

<div class="col-md-12">
  <div class="tablist-content" id="list1">
    List one content
  </div>
  <div class="tablist-content" id="list2">
    List Two content
  </div>
</div>

</div>

Answer №1

Utilize data attributes

No necessity to verify if checked or not.

$('.tablist').on('click', 'input', function() {
  $(".tablist-content").hide()
  $("#"+$(this).data("id")).show()
});
.tablist-content {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tabWrapper">
<ul class="list-unstyled tablist">
  <li>
    <input type="radio" name="tablist" data-id="list1">
    <label for="tablist1">List1</label>
  </li>
  <li>
  <input type="radio" name="tablist" data-id="list2">
    <label for="tablist2">List2</label>
  </li>
</ul>

<div class="col-md-12">
  <div class="tablist-content" id="list1">
    Content for List one
  </div>
  <div class="tablist-content" id="list2">
    Content for List Two
  </div>
</div>

</div>

Answer №2

If you want to find out the index of the radio button that was clicked, you can use the .index() method.

Another option is to utilize the change event, which only triggers when a radio button changes from unchecked to checked. In contrast, the click event will trigger regardless of whether the radio button was previously checked or not.

$('.tablist').on('change', 'input', function() {
    var index = $('input[name=tablist]').index(this);
    $('.tablist-content').hide().eq(index).show();
});
.tablist-content {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tabWrapper">
<ul class="list-unstyled tablist">
  <li>
    <input type="radio" name="tablist" id="tablist1">
    <label for="tablist1">List1</label>
  </li>
  <li>
    <input type="radio" name="tablist" id="tablist2">
    <label for="tablist2">List2</label>
  </li>
</ul>;

<div class="col-md-12">
  <div class="tablist-content" id="list1">
    Content for List One
  </div>
  <div class="tablist-content" id="list2">
    Content for List Two
  </div>
</div>;

</div>

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

What is the best way to determine and showcase the hours that have passed since the user's initial visit to the website?

Can someone provide guidance on how to finalize the hoursSinceFirstVisit() function implementation? Additionally, what content should be displayed on my HTML page? $(document).ready(function() { startTimer(); }); function startTimer() { setInte ...

To ensure a rectangular image is displayed as a square, adjust its side length to match the width of the parent div dynamically

How can I make the images inside my centered flexbox parent div, #con, be a square with side length equal to the width of the parent div? The image-containing div (.block) is positioned between two text divs (#info and #links). I want the images to be squa ...

Form submitted using ajax did not receive a success confirmation

I have been working on creating a contact form for WordPress using ajax, but I am encountering an issue with the success function in jQuery not appending the confirmation message. PHP Function add_action('wp_ajax_submit_form', 'submit_form ...

generate a customized synopsis for users without storing any data in the database

In order to provide a summary of the user's choices without saving them to the database, I want to display it in a modal that has already been created. Despite finding some sources online, none of them have worked for me so far. Below is my HTML: &l ...

maintaining a specific variable within React

I am working on integrating pagination into my app. I have written the code below, but unfortunately, I am encountering an issue. Below is the implementation of my useEffect: useEffect(() => { let x = null; const unsubscribe = chatsRef . ...

Saving an incremented number using Vue JS in Firebase database

I have a VueJS app integrated with Firebase JSON database where I'm trying to implement a feature that allows users to update the vote count of a comment by clicking an arrow (similar to upvotes on this website). The function works properly, but the V ...

What is the limit for table size in HTML5 Web SQL DB?

Currently, I am in the process of developing a rather intricate HTML5 web app that obtains its data from a Web Service to populate the Web SQL database. Initially, everything was running smoothly with test data. However, when I attempted to use actual dat ...

Issues with data binding in Angular2 are arising specifically in IE11

After successfully loading the application on Chrome, Firefox, and Edge, I encountered difficulties when trying to load it on IE11. The data bindings were not created properly, despite the internal data being fetched correctly through a websocket connectio ...

The functionality of remotely accessing autocomplete in Angucomplete Alt is currently not functioning properly

I'm currently experimenting with AngularJS autocomplete using Angucomplete Alt. I've copied the same code and running it on my local host, but unfortunately, no results are being displayed. When searching for the term 'ssss', an error ...

Error: The text value is not defined

Hello, I am currently working on retrieving the selected value of an input when the input is focused with the tab key. Below is my code: HTML <input id='texteb' type="text" value='' /> <button> click </button> JS ...

Unexpected issue with Ionic 4 subarray returning as undefined even though the index is accurate

When attempting to use console.log to view the value, I noticed that the value of noticeSet2[index] is undefined. However, when I print noticeSet, all the data in the array is displayed. Additionally, after printing the index using console.log, it correctl ...

What is the best way to create a time delay between two consecutive desktop screenshot captures?

screenshot-desktop is a unique npm API that captures desktop screenshots and saves them upon request. However, I encounter the need to call the function three times with a 5-second delay between each call. Since this API works on promises, the calls are e ...

Automate the execution of webdriver/selenium tests when a form is submitted

I am currently faced with a challenge in setting up an application that will automate some basic predefined tests to eliminate manual testing from our workflow. The concept is to input a URL via a user-friendly form, which will then execute various tests ...

Utilizing hyperlinks within NicEdit content and managing events with jQuery

I am using nicEdit, a rich editor, on my website to insert hyperlinks into the content. While I can successfully add hyperlinks using the setContent() method after initializing nicEdit, I am facing issues with handling click events for hyperlinks that have ...

Gain access to PowerBI reports effortlessly without the need to input any credentials

Seeking guidance on calling Power BI reports from an ASP.NET C# web application while passing credentials, specifically without utilizing Azure AD. Access has been granted to certain users in the Power BI Service workspace with view permissions. We aim t ...

Is it possible to integrate external search functionality with Vuetify's data table component

I am currently working with the v-data-table component from Vuetify, which comes with a default filter bar in its properties. This table retrieves data from a local JSON file. The issue arises when I have another external component, a search bar created u ...

appending a set of parameters to a website address

I am currently developing an app in a Node/Express/Jade environment. Imagine that I launch my app and navigate my browser to the following URL: /superadmin/?year=2012 Upon reaching this page, I encounter a list of objects sorted in a default order. Ther ...

EJS file not displaying stylesheets and images correctly during rendering

I'm currently in the process of building a website, but when I try to render an ejs file (index.ejs), only the HTML portion is displayed without showing any stylesheets, fonts, or images. Here is the code snippet for linking the stylesheets: <!D ...

AngularJS array not refreshing following an AJAX request

Currently, I am still in the process of familiarizing myself with Angularjs and actively learning about its functionalities. One issue I have encountered is that when I define an array and loop through it using "ng-repeat," the items within ng-repeat fail ...

What is the best way to implement auto-saving functionality for multiple form fields in a React application?

Whenever I make changes to the first and second columns of an item in a text field, the onBlur event triggers an auto-save. This results in the entire row being reloaded due to the update caused by the first column's save. Is there a way to prevent t ...