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

Issues with the alignment of columns using Bootstrap framework

I've created a design in Photoshop using the Bootstrap 12-column guide, but when I try to implement it using Bootstrap, the results are completely off. https://i.stack.imgur.com/vQwOt.png Here's my HTML code: <!DOCTYPE html> <html lan ...

CSS techniques for aligning content

I am currently working on designing a website template, and I have encountered an issue with positioning three individual columns that contain blocks of content. My objective is to have the first block of content in each column start at the top of their re ...

Build a bootstrap table with rounded corners

Currently, I am utilizing Bootstrap 5 and have the table code below: .reasonCode-table { padding: 8px; border-collapse: separate; } .reasonCode-table th { border: 2px solid #7a7878; padding: 8px; border-radius: 2px; border-collapse: collaps ...

Ways to prevent animations from displaying solely in IE

Is there a way to remove a keyframe animation if the browser is IE, while keeping it for Chrome, Safari, and FireFox? The animation I am referring to is defined as follows: // Animations @-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } } ...

Guide to aligning Material UI card in the center (React)

I've been struggling to find a solution for centering a Material UI card in React. Any assistance would be greatly appreciated! Thank you :) link to image on website <Grid container justify="center"> <Card s ...

What is the process for rendering content with renderajax?

I'm having trouble trying to render the view create.php using renderAjax in the controller. I've tried different methods but can't seem to make it work properly. The problem is that the js files (select2, datatables, etc) are not loading. I ...

Adding negative values to the Tailwind CSS utility plugin is a simple process that can greatly enhance

Adding Negative Values to Tailwind CSS Utility Plugin Quick Summary: I've developed a custom Tailwind utility plugin that includes numeric values. I'm looking for a way to introduce negative numbers by adding a - at the start of the class, simi ...

Creating a dynamic rectangular design with a taller height than width, featuring perfectly centered content

My website needs a responsive rectangle where I can easily adjust the height and width. However, when I try to rotate the rectangle, the content also rotates 90 degrees. Can anyone help me with this issue? Thank you in advance for any assistance. Snippet ...

Change the selection so that only the initial one appears in gray

Is there a way to make the text inside a select field gray out when the first option is selected? Can this be accomplished with just CSS or does it require JS? I have attempted altering the style of the first option, but it only affects the text color in ...

Having difficulty retrieving/binding the correct Entity Id in JQuery, consistently retrieves the first item Id from the iteration

Within my PartialView, I am looping through a Collection of Entities and displaying them in an Html Table. In one column of this table, there is an element with a font awesome class (fa fa-times-circle). I am setting the "id" property of this to the "I ...

Leveraging jQuery for Sending Form Data to an ASP.NET ASMX Web Service

I am working on creating a straightforward login form where the submit button will post form data to a method in an asmx file. Unfortunately, I encounter an error whenever I try to post from inside a form tag. Posting outside of the form tags functions ...

Utilizing Various jQuery Selectors for Option Values

I'm currently facing a challenge with including extra value selectors in jQuery. My goal is to include option[value="18:00"] so that if option [value="17:00"] is not chosen, it will trigger the function when 18 is selected. Below is the code snippet: ...

Amend and refresh information using AJAX technology

My code isn't working as expected when I try to use AJAX to retrieve data from an editable form and update it in the database. Can someone help me find the issue? Below is the code I'm using: <?php $query = db_get_list("SELECT * FROM ...

Is there a way to show textboxes stacked on top of each other without causing them to

Here is the HTML snippet I am working with: <div> <p><label>Faculty <input type="text" class = "f"></label></p> <p><label >Department<input type="text" class = "f"></label></p> ...

Switch body class when the navbar's collapse show class is toggled

There are numerous methods to accomplish this task, but I am seeking the most optimal and efficient approach. My goal is to toggle a custom body class when the .navbar-toggle triggers the .show class on the .navbar-collapse element. I'm hesitant abo ...

Integrate the element offset into jQuery's offset calculations

I'm new to utilizing jQuery and currently facing a challenge in determining the correct offset for a specific div element within the body. My goal is to make this particular div stick to its position as I scroll down past its designated top offset. A ...

Employ JQuery to create a smooth fading effect on a button when hovering over it, and then gradually fade it out

Is there a way to make a button fade in when I hover over an image and then disappear once I hover off? I have tried using the hover() function with a button class of "goto" (#goto), but can't seem to get it to work. Would combining fadein and fadeout ...

The Django server fails to display the CSS files upon activation

Despite having all the static files in place, only the plain HTML loads without any styles for some unknown reason. I've attempted using collectstatic and even setting up a new project, but to no avail. STATIC_URL is also properly specified along with ...

Whenever I try to upload a file using ajax in MVC, I consistently encounter a null Request.Files in action side

I am facing an issue with uploading an image using ajax mode in MVC. I have tried a method where everything seems to work fine in the JavaScript code - it gets the formdata and sends the ajax request to the controller correctly. However, in my controller, ...

Guidelines for redirecting a page after a jQuery ajax call is made?

I'm working on a login form code and facing an issue where, after the statement is true, it doesn't redirect to the home page. Instead, it just displays the home page on my index page. How can I redirect jQuery Ajax to another page after the sta ...