Is the tab not displaying correctly when using Bootstrap 5 button functionality?

With Bootstrap 5, I have a modal that contains two tabs for login and register. However, I am facing an issue where the tab is not displaying correctly based on the button click.

The desired behavior is that clicking on the login button should activate the login tab within the modal, and clicking on the register button should activate the register tab.

An error message appearing in the console: Uncaught TypeError: Cannot read property 'show' of null

Here is the relevant code snippet:

 $('.register-btn').click(function() {
        $('#loginModal').modal('show');
        var triggerEl = document.querySelector('[data-bs-target="#register"]')
        bootstrap.Tab.getInstance(triggerEl).show()
    })
    $('.login-btn').click(function() {
        $('#loginModal').modal('show');
        var triggerE2 = document.querySelector('[data-bs-target="#login"]')
        bootstrap.Tab.getInstance(triggerE2).show()
    })
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c2e2323383f383e2d3c0c79627c627d">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6b4b9b9a2a5a2a4b7a696e3f8e6f8e7">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>

<button type="button" class="btn btn-primary register-btn">
        Register
    </button>
    <button type="button" class="btn btn-primary login-btn">
        Login
    </button>

<div class="modal fade" id="loginModal" tabindex="-1" aria-labelledby="exampleloginModal" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            ...
        </div>
    </div>
</div>

Your assistance is much appreciated!

Answer №2

If you want to simulate clicking the tab, triggering a click event can do the trick.

$(".register-btn").click(function () {
  $("#register-tab").trigger("click");
  $("#loginModal").modal("show");
});
$(".login-btn").click(function () {
  $("#login-tab").trigger("click");
  $("#loginModal").modal("show");
});
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ceee3e3f8fff8fedfcac7dfcacfaafdc6d9dfdce6">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12707d7d66616660736252273c223c23">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>


<!-- Button trigger modal -->
    <button type="button" class="btn btn-primary register-btn">
        Register
    </button>
    <button type="button" class="btn btn-primary login-btn">
        Login
    </button>

<!-- Modal -->
 <div class="modal fade" id="loginModal" tabindex="-1" aria-labelledby="exampleloginModal" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-0">
                <div class="row m-0">
                    <div class="col-md-6 p-0">
                        <img src="images/login-img.png" class="img-fluid" alt="">
                    </div>
                    <div class="col-md-6">
                        <div class="login-right-body">
                            <ul class="nav nav-pills nav-fill" id="myTab" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="login-tab" data-bs-toggle="tab" data-bs-target="#login" type="button" role="tab" aria-controls="login" aria-selected="true">Login</button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="register-tab" data-bs-toggle="tab" data-bs-target="#register" type="button" role="tab" aria-controls="register" aria-selected="false">Register</button>
                                </li>
                            </ul>
                            <div class="tab-content" id="myTabContent">
                                <div class="tab-pane fade show active" id="login" role="tabpanel" aria-labelledby="login-tab">
                                    <form>
                                        <div class="form-group custom-form-group">
                                            <label>Mobile Number</label>
                                            <input type="text" class="form-control">
                                        </div>
                                      
                                        <div class="form-group custom-form-group">
                                            <button class="btn btn-primary btn-block">Login</button>
                                        </div>
                                    </form>
                                </div>
                                <div class="tab-pane fade" id="register" role="tabpanel" aria-labelledby="register-tab">
                                    <form>
                                        <div class="form-group custom-form-group">
                                            <label>Full Name</label>
                                            <input type="text" class="form-control">
                                        </div>
                                       
                                        <div class="form-group custom-form-group">
                                            <button class="btn btn-primary btn-block">Register</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
         
        </div>
    </div>
</div>

Answer №3

To make tabs tabbable, follow these steps: 1) Implement JavaScript for tab functionality, and then 2) Activate each individual tab (as the triggers you are referring to are not present).

Visit this link for more information on Bootstrap tabs.

Ensure that you enable tabbable tabs using JavaScript.


// JavaScript Implementation

// Enable tab functionality through JavaScript (each tab must be activated separately):

var triggerTabList = [].slice.call(document.querySelectorAll('#myTab a'))
triggerTabList.forEach(function (triggerEl) {
  var tabTrigger = new bootstrap.Tab(triggerEl)

  triggerEl.addEventListener('click', function (event) {
    event.preventDefault()
    tabTrigger.show()
  })
})

// Individual tabs can be activated in various ways:

var triggerEl = document.querySelector('#myTab a[href="#profile"]')
bootstrap.Tab.getInstance(triggerEl).show() // Select tab by name

var triggerFirstTabEl = document.querySelector('#myTab li:first-child a')
bootstrap.Tab.getInstance(triggerFirstTabEl).show() // Select first tab

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

Implementing multiple filters with jQuery

Make a Selection `<select class="form-control" id="technology"> <option name="sort" value="2g" id="2g"gt;2G</option> <option name="sort" value="3g" id="3g"&g ...

Using an external HTML file to import a template into Vue.js single file components

I've been tackling a Vuejs project that involves using vue-property-decorator in single file components. I'm trying to figure out how to import the template from an external HTML (or different) file, but so far I haven't found a solution. I& ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

How to implement a service function to handle $http responses in a controller

Is it possible to use $http only for my service and not the controller? I am getting undefined in my console.log when trying to display data in a $scope. Here is my code: app.controller('adminControl', ['$scope','$routeParams&apo ...

Remove leading spaces before text

Is there a way to remove spaces before text only? " with spaces between" What I want: "some text with spaces between" I have tried using text.replace(/\s/g, '') but it doesn't give the desired result: "sometextwithspacesbe ...

Enclose the content in a div element and then append it using the appendTo

Attempted to enclose appendcontent within a image div, but received [object Object] as the output. $("<div class=image>" + appendcontent + "</div>").appendTo($('.outside')); Is there a way to insert $(appendcontent) inside $("<d ...

Arranging numerous Text elements within a solitary Drag and Drop container with the z-index property

I am facing a challenge with stacking twelve arguments in no particular order on a drag and drop element. The texts overlap each other, making it difficult for the end user to see them clearly when dragging and dropping. Is there a way to stack texts using ...

What is the correct way to use fitBounds and getBounds functions in react-leaflet?

I'm struggling with calling the fitBounds() function on my Leaflet map. My goal is to show multiple markers on the map and adjust the view accordingly (zoom in, zoom out, fly to, etc.). I came across an example on How do you call fitBounds() when usi ...

Continuously generate new objects every second

I am working on a function that involves adding the RandomBlock object to the scene and then moving it downward on the screen. function enemyPaddleMovement() { scene.add(RandomBlock); RandomBlock.translateX(-8); } The RandomBlock object is created using ...

Struggling to increment the badge counter in a React Typescript project

I'm a bit unsure about where to apply the count in my Badge Component. The displayValue should include the count, but I'm struggling with how to implement it. UPDATE: The counter is now in place, but when I decrease the count and it reaches 0, t ...

Is this AJAX request properly formatted?

I am attempting to send an array of variables to my CakePHP action for editing purposes. The array is created from the ids of table rows. Below is the javascript code snippet that can be found in my index.ctp file. <script type="text/javascript"> $( ...

Tips for personalizing Twitter Bootstrap popover concealment animation

Currently, I am interested in creating a unique hide animation for my popover. Instead of directly modifying bootstrap.js, I would like to implement my own custom code. $.fn.popover = function (option) { return this.each(function () { ...

Google's AJAX crawling scheme using the shebang syntax is failing to crawl pages

I have incorporated Google's shebang '#!' syntax for ajax crawling on my website. Both ends of the system have been set up as per the guidelines provided at https://developers.google.com/webmasters/ajax-crawling/docs/specification This mea ...

AngularJS: Issue with ng-show and ng-click not functioning when button is clicked

I have a specific requirement where I need to display and hide the description of each column in a table when a button is clicked. Here is the visual representation of what I have: the table In my HTML code, I have defined a button with ng-click as a func ...

Stripping away HTML tags from a JSON output

I'm attempting to retrieve a JSON result using jQuery. $.ajax({ type: "GET", url: "http://localhost:8080/App/QueryString.jsp?Query="+query, contentType:"text/html; charset=utf-8", dataType: "json", success: function(json) { if(data!="") ...

The <br/> tag is not functioning properly when retrieving text from a MySQL query

Currently, I am involved in a project that involves an A.I pushing text onto a MySQL database. Our goal is to display the ongoing writing process on a webpage. We are still actively working on this. We are retrieving the data and regularly checking the da ...

Using Jquery to automatically populate an input field if the user already exists

I'm currently working on populating a form if the user input for name and firstname already exists in my database. However, I am facing an issue with my JavaScript program where it fails to check if the name and firstname combination already exists i ...

Can you explain the variances between ngx-translate and ngx-i18next for me?

As ngx-i18next serves as a wrapper for i18next, I am curious about the specific differences in translation capabilities between ngx-translate and i18next. ...

Is it possible for me to determine when all images have finished loading in order to update the isLoaded variable to true?

I am using the template below: <template> <div v-if='isLoaded'> <div @click='selectSight(index)' v-for='(sight, index) in sights'> <img :src="'https://maps.googleapis.com/maps ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...