Preventing navigation to other tabs in Bootstrap tabs during validation

I am running validation on tab one input fields when the second tab is clicked.

Please take a look at my HTML code:

                                    <ul class="nav nav-tabs makeblock" role="tablist">
                                        <li class="nav-item"> <a class="nav-link active" href="#StuAdmn" role="tab" data-toggle="tab">Admission</a> </li>
                                        <li class="nav-item" id="tabStudentGeneralDetails"> <a class="nav-link" href="#stuGenDetails" role="tab" data-toggle="tab">General </a> </li>
                                        <li class="nav-item"> <a class="nav-link" href="#stuParentDetails" role="tab" data-toggle="tab">Parent</a> </li>
                                        <li class="nav-item"> <a class="nav-link" href="#joingDetails" role="tab" data-toggle="tab">Joining</a> </li>
                                        <li class="nav-item"> <a class="nav-link" href="#stuAdrs" role="tab" data-toggle="tab">Address</a> </li>
                                        <li class="nav-item"> <a class="nav-link" href="#feeDetails" role="tab" data-toggle="tab">Fee </a> </li>

                                    </ul>
                                </div> 

//tab 1 div
<div role="tabpanel" class="tab-pane active fade in" id="StuAdmn">
    <div class="col-md-4">
         <label for="firstName"><span>*</span>First Name:</label>
         <input type="text" class="form-control only-alpha" placeholder="First Name" id="firstName">

       </div>
</div>
//tab 2 div
 <div role="tabpanel" class="tab-pane fade" id="stuGenDetails">
</div>

I am validating the field with id="firstName" when id="tabStudentGeneralDetails" tab is clicked. I do not want to switch to the clicked tab unless the fields in the previous tabs are validated.

I have attempted the following code:

$(document).on("click",".newSec #tabStudentGeneralDetails",function(e){
    var firstName=$(".newSec #firstName").val();
    if(firstName == "")
        {
        $(this).find("a").attr("aria-expanded",false);
            alert("Please enter the student's first name!"); 

        } 
});

With the above code, I am able to validate the fields in the first tab but unable to prevent moving to the clicked tab if the data in the first tab is incorrect.

Could someone provide assistance with this?

Thank you.

Answer №1

When working with Bootstrap, there are two ways to activate tab navigation.

  • To activate the tab navigation in your HTML, you can specify data-toggle="tab".
  • Alternatively, you can manually activate the tabs using JavaScript with the .tab() function.

In the provided example, the data-toggle="tab" method was used, automatically activating the tab navigation with limited control over its behavior. To have more control based on certain criteria, the second method of manually activating tabs is recommended.

Below is a basic example code snippet demonstrating how to activate tabs using JavaScript instead of data-toggle="tab". The code includes a function called isValid to validate form inputs and ensure the tab navigation only functions correctly when the validation criteria are met.

$('#myTab a').on('click', function(e) {
  e.preventDefault();
  if (isValid()) {
    $(this).tab('show');
  }
});

function isValid() {
  const text = $("#homeText").val();
  if (text.length === 0) {
    return false;
  }
  return true;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" id="home-tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="profile-tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Profile</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="contact-tab" href="#contact" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
  </li>
</ul>
<div class="tab-content" id="myTabContent">
  <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
    Home Tab Content<br>
    <input type="text" id="homeText" /> Enter some value
  </div>
  <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">Profile Tab Content</div>
  <div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">Contact Tab Content</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

Having trouble sending the information to Parse.com using the website

I am a beginner with the Parse database and I am currently working on implementing a code that allows users to sign up, with their information stored in the Parse database. However, I am encountering an issue where the values are not uploading as expected. ...

What is the best way to test speedy AJAX response times using Webdriver.io?

Currently, I am creating Cucumber.js tests using Webdriver.io. Everything seems to be going smoothly, but I'm encountering an issue with the mock server responding too quickly with AJAX. The "Loading..." message is not visible because the content load ...

Transform the Nodejs server into a reusable Node module

Can a nodejs API server be transformed into a node module for use in other projects with minimal code modifications? Additional Information: The node js server contains various APIs (get, post, put). If I integrate this server as a node module within anot ...

Guide to setting up an object array in JavaScript with unique child elements and no duplicate values

I have an array that looks like this: sampleArray = ["x", "y", "z". "a.b", "a.b.c", "a.b.d", "a.e.f", "a.e.g"] However, I am aiming to transform it into the following structure, or something similar to it: newArray: [ { "x": [] }, ...

Unable to send parameters via URL when making an Ajax request in Rails

Struggling to pass a parameter through a URL in an Ajax request that's triggered by a confirmation dialog. Need the value of that parameter in my Rails controller upon successful request but can't seem to make it work. Tried the following code s ...

Trouble with Updating Div Content?

Within my HTML code, I have included this JavaScript snippet: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script> var auto_refresh = setInterval( function() { $('#loaddiv').fadeOut ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

Using a three.js texture with a JSON object

Currently, I am working on a customization project where I am using three.js to export an HTML5 canvas as a 3D preview. My goal is to have the texture placed only on the front side, but it seems to appear on all sides instead. This is the code I am using: ...

What strategies can I use to prevent the need to create new instances of my service and repository for every

Currently, I am delving into the world of JavaScript using the Express.js Framework. My current learning project involves creating a simple restaurant application to grasp the ins and outs of CRUD operations related to ingredients. I have meticulously craf ...

Tips for implementing xpath in module.exports with mocha javascript

Currently, I am utilizing mocha in conjunction with Node.js and have encountered a challenge. In my scenario, I need to use the XPath defined in one test file (verification.js) and apply it in another file (test.js). The issue arises from the fact that the ...

Using JQuery, identify cells located in the first column of a table excluding those in the header section

In the past, I had code that looked like this: $(elem).parents('li').find(...) I used this code when elem was an item in a list, making it easy to reference all items in the list. But now, I've made some changes and decided to use a table ...

"Utilize the power of the ajaxform jQuery plugin to automatically reset form fields

Initially, I'd like to emphasize that this is an original inquiry. My predicament is as follows: I have a chatroom php script where I utilize the ajaxForm jQuery plugin to seamlessly send new messages without having to reload the entire page. Howev ...

Using global variables for mocha testing (and babel setup)

Currently, I am developing a library using es6 and transpiling it with babel via webpack and npm. However, I have encountered an issue where my library has a dependency on some code that cannot be modified but is required for my library to function properl ...

Unable to send email through Ajax/PHP contact form

It's quite amusing that it worked perfectly for one evening. After reaching out to my host, they assured me that there should be no issues with it not working. I even tried testing it in Firebug, but it appeared to be sending successfully. Additionall ...

Could somebody please clarify the purpose of Bootstrap's `_root.scss` file?

After reading through the Bootstrap introduction [1], I added the following code snippet to my .html file: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384- ...

Unable to locate module within a subdirectory in typescript

The issue I'm facing involves the module arrayGenerator.ts which is located in a subfolder. It works perfectly fine with other modules like Array.ts in the parent folder. However, when I introduced a new module called Sorting.ts, it started giving me ...

I often find that jscodeshift consistently avoids processing my JavaScript files

I am currently in the process of updating my react application to the newest version of Material-UI. I came across a migration helper script using jscodeshift within the material UI project. (https://github.com/mui-org/material-ui/tree/master/packages/mate ...

Change the keys of the object in the return statement

Scenario Imagine a scenario where a method called matter is returning an object in the form of return {content, data} Issue There is a conflict when the method is called a second time, as it overwrites any previous variables that were set from the return ...

Guide to utilizing AJAX to retrieve a value from a controller and display it in a popup

I need assistance with retrieving data from a controller and displaying it in an HTML pop-up when a button is clicked. Currently, the pop-up shows up when the button is clicked, but the data is not being loaded. I would like the values to be loaded and d ...

In a functional component in Typescript, what data type should be used for a parameter that accepts an array of objects?

const FormData = ({ dataArray }: object[]): JSX.Element => { console.log("Array of Objects",dataArray) //This is a large form component.... }); The dataArray contains multiple objects, how can I specify a specific type for these components ...