How to automatically set a default bootstrap tab upon page load using an MVC JsonResult responseData

I'm looking to enhance the user experience on my dashboard by allowing users to set their preferred default tab view upon logging in. Using an AJAX call to retrieve the value from the database in MVC, I am working on the JS/Razor side of things to make it functional. Any insights or suggestions on how to tackle this issue would be highly appreciated.

Code

//Load Account Preferences
        function loadAccountPreferences() {
            $.ajax({
                type: "GET",
                dataType: 'json',
                url: '/JsonUserSettings/GetUserSettings',
                success: function (result) {
                    loadDefaultTab(result);                    
                },
                error: function(error) {
                    alert(error);
                }
            });
        }

        loadDefaultTab = function (tabId) {

            $("#dashboardTabs a: tabId").tab('show'); 
        }
    

Answer №1

After experimenting with the code, I managed to find a solution that works! One improvement would be to follow Adriani6's suggestion of storing the default tab value in the database with a # symbol before the tab name. Here is the updated code:

  //Retrieve Account Preferences
    function retrieveAccountPreferences() {
        $.ajax({
            type: "GET",
            dataType: 'json',
            url: '/JsonUserSettings/GetUserSettings',
            success: function(result) {
                displayDefaultTab(result);
            },
            error: function(error) {
                alert(error);
            }
        });
    }

    displayDefaultTab = function(tabId) {
        let defaultTab = '#' + tabId;
        $('.nav a[href="#"]').attr("href",defaultTab).tab('show');
    }

Answer №2

I previously mentioned in my comment that the code you posted is incorrect because it will always display the last tab. Here's why...

Let's break down your code to understand what's happening...

$('.nav a[href="#"]') - This line selects all elements (potentially more than one) that are <a> tags with an href value of "#" and are within an element with the class nav.

Consider this example HTML structure...

<div class="nav">
    <a href="#">First</a>
    <a href="#">Second</a>
    <a href="/Settings">Third</a>
    <a href="/Help">Fourth</a>
</div>

Your array of elements would include "First" and "Second", and any operations on this array would affect both elements.

With an array of elements identified at this point, the next function performs the same action on each element in the array, resulting in every tab having a href attribute set to defaultTab.

Lastly, when you call .tab('show'), since it's an array and likely only allows one tab to be visible at a time, it consistently displays the last tab.

If your href values are already assigned and not dynamically generated (as your code suggests by applying the same href to all tabs), consider using the selector I suggested in your question:

$("#dashboardTabs a: " + tabId).tab('show');

Your revised solution should resemble this:

$('.nav a[href="'+defaultTab+'"]').tab('show');

This approach achieves the same outcome as before but now matches the intended href values without altering any existing elements.

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

The link that has been clicked on should remain in an active state

Is there a way to make the link that is clicked on active? I have attempted various scripts but have had no luck in getting the desired effect. Can anyone identify what might be causing the issue? $("a").click(function () { if ($(this).hasClass("acti ...

Modifying SASS variable values based on the presence of specific text in the page URL

How can I utilize the same SASS file for two different websites with similar functionality but different color schemes? My goal is to dynamically change the color based on the URL of the page. However, I am facing challenges in extracting the page URL from ...

The jQuery function fails to execute when the script source is included in the head of the document

I'm relatively new to working with scripts and sources, assuming I could easily add them to the header and then include multiple scripts or functions afterwards. Everything seemed to be working fine at first, but now I've encountered a problem th ...

Performing calculations using jQuery and organizing sub-totals into groups

I am currently developing a web application and aiming to incorporate an invoice calculation feature with sub-groups. My goal is to have the total result of both group-totals and sub-totals at the end. Here is my progress so far: Check it out here $(func ...

Issue with Datatables FixedColumns plugin in IE8/7 and Firefox

I am encountering issues with the FixedColumn plugin on IE8, IE7, and Firefox. All of them are causing my table to malfunction, displaying the following error: Error: Invalid argument. Line: 566 Char: 3 Code: 0 URI: ./resources/javascript/dataTable/Fixed ...

Issues have been encountered with jQuery on function when it comes to dynamically inserted elements

I have been trying to utilize the .on method for dynamically created elements, but it doesn't seem to be working as expected. I am using a selector though :) $(".metadata").on("click", "i.icon-remove", function () { console.log("what"); $(thi ...

Tips for ensuring the drop down button remains selected

My goal is to keep the sorting drop-down button selected after clicking on it, instead of resetting back to "All". Below are my HTML, CSS, and jQuery code. You can view the functionality on my website here: jQuery/Javascript: $(document).ready(function($ ...

Using arrow keys and return to effortlessly navigate through text input fields

Currently, I am working on developing a jQuery-based navigation system for switching between multiple input fields. The first part of the code is functioning correctly, allowing users to navigate downwards using either the down arrow or the return key. H ...

Incorporating jQuery into Rails 6.1

I encountered some difficulties while setting up jQuery in rails 6.1, even though I believe it's configured correctly. Below are the steps I've taken: Installed yarn add jquery 2. In config/webpack/environments.js, I made the following changes ...

Aligning icons side by side using only CSS styling

I'm having trouble positioning icons next to each other horizontally and they keep stacking on top of one another. Can you please review my CSS code to see if I made a mistake? Here is the CSS: #social { top:20px; left:30px; height:32px; width:200p ...

The <nav> and <section> elements are not appearing on the page

Website: CSS: Hello there! I am experiencing an issue where the nav and section elements are not displaying on my website. They seem to only show the height and background-color attributes. Interestingly, they appear correctly on my old Firefox version ( ...

Ways to eliminate a textbox from an HTML table using jQuery or JavaScript while retaining the textbox values

Currently, I am facing a task where I have a table with a column filled with textboxes. My goal is to eliminate the textboxes using jQuery/JavaScript while retaining the values within them. Here are a couple of methods I have attempted: // removes both t ...

Error: The term "Particles" has not been defined

I'm attempting to integrate code from a website into my project, but encountered an error when the particles failed to run after adding it. I downloaded and installed particle.js from "https://github.com/marcbruederlin/particles.js/issues" for this pu ...

Looking for a prerequisite for running this script?

Seeking assistance from a skilled Javascript expert. I specialize in template development and utilize a specific script to display my footer link in all the free templates I create. If someone attempts to remove the footer link, their site will be redirec ...

Removing a row from an HTML table using JavaScript

I have a piece of JavaScript code that is responsible for managing an HTML table. One of the functionalities it needs to support is deleting a row from the table. Currently, I am using the following snippet of code to achieve row deletion: var rowToDele ...

Move Picture with Click (like the action on Google Maps)

Currently on the lookout for some code that will enable me to manipulate a floor plan in a manner reminiscent of the one showcased at whitehouse.gov I am in the process of coding a website that would benefit from integrating a similar function with their ...

Embarking on the GSAP journey

I'm attempting my first animation using GSAP, but no matter what I try, nothing seems to be working. I've even tried using example code without success. Within my PHP file, I have the following code snippet: <head> <script src="https:/ ...

Validate forms using jQuery with the power of ajax

Is there a way to effectively check for the existence of a username? I want to increment a variable called "form_error" if the username already exists. If "form_errors" is greater than 0, I need the code to stop and return false. However, when I use an Aj ...

Improving large JSON data with multiple calls

In my Java/Spring web application, I have implemented a feature where each user can manage their own word list. Whenever a user adds or removes a word, an AJAX call is made to send a JSON object with the word information to the server for processing. The s ...

Make sure that the input field and label are aligned side by side in the

Is there a way to arrange the following HTML in the specified layout? <div> <div> <label>Counterparty</label> <input id="paymentsApp-inpt-cpty" ng-model="selectedPaymentCopy.counterparty" ng-required="true" ...