What is the best way to define the active <li> tab using JQuery?

Initially, my HTML code includes a set of <li> elements that I want to dynamically add to the existing <ul>.

<ul class="tabs" id="modal_addquestion_ul">
    <li class="tab-link current" data-tab="multipleChoice">Multiple Choice</li>
    <li class="tab-link" data-tab="trueOrFalse">True or False</li>
    <li class="tab-link" data-tab="fillInTheBox">Fill in the Box</li>
</ul>

The current tab is initially set to Multiple Choice.

To achieve this dynamic addition, I utilize a JQuery method that retrieves data from a database query.

function loadQuestionTypesToULTab(ULId){
    $.ajax({
        url: 'controller/get_all_question_types.php',
        type: 'POST',
        dataType: 'json',
        success: function (questionTypeData) {
            console.log(questionTypeData);
            var len = questionTypeData.length;
            clearListItemsOf(ULId);
            for (var i = 0; i < len; i++) {
                var questionTypeId = questionTypeData[i]['questionTypeId'];
                var questionType = questionTypeData[i]['questionType'];
                var listItem = $('<li></li>').val(questionTypeId)
                                .text(questionType).addClass('tab-link').attr('data-tab',questionType);
                $(ULId).append(listItem);
            }
        },
        error: function (x, e) {
            handleError(x, e);
        }
    });
}

Upon inspection using Google Chrome's developer tools, the generated <li> elements match the original structure closely. However, the "current" status is not applied correctly to the Multiple Choice tab.

Here is the output observed in Chrome's inspector:

<li value="1" class="tab-link" data-tab="Multiple Choice">Multiple Choice</li>
<li value="2" class="tab-link" data-tab="Fill in the Box">Fill in the Box</li>
<li value="3" class="tab-link" data-tab="True or False">True or False</li>

The goal is to have the Multiple Choice tab marked as "current" within the class attribute.

Attempts to include the "current" class using .addClass('tab-link current'); have only resulted in the omission of "current" from the class attribute in the HTML markup.

I appreciate any guidance on how to resolve this issue.

Answer №1

As mentioned, it is important to include the 'current' class specifically in your code snippet.

While you attempted to use addClass('tab-link current'), this line seems disconnected from the rest of your code. The commented-out line appears outdated and could apply to all items rather than a specific one.

To assign the current class to a particular item, consider implementing something like this (where the first item receives the current class):

success: function (questionTypeData) {
        var len = questionTypeData.length;
        clearListItemsOf(ULId);
        for (var i = 0; i < len; i++) {
            var questionTypeId = questionTypeData[i]['questionTypeId'];
            var questionType = questionTypeData[i]['questionType'];
            var listItem = $('<li></li>').val(questionTypeId)
                            .text(questionType).addClass('tab-link').attr('data-tab',questionType);
            if ( i == 0 ){
                listItem.addClass( 'current' );
            }
            $(ULId).append(listItem);
        }
    },

Answer №2

Experiment with using .addClass('tab-link'); followed by .addClass('current'); These two steps should produce the desired outcome. Alternatively, you can achieve the same result by chaining both methods together like this: .addClass('tab-link').addClass('current');

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

When utilizing the getIntersectionList function, IE 9 may experience a malfunction and cease functioning

I am currently working with SVG code and JavaScript, trying to achieve a specific intersection result. <svg id="svgSurface" width="500" height="500"> <defs> <marker id="Triangle" viewBox="0 0 20 20" refX="0" refY="0" markerUnits ...

Determine whether all elements in the array are false using Array.every()

Below is an example of an array: myArray = {firstValue: false, secondValue: false, thirdValue: true, forthValue: false}; The goal is to determine if every value in the array is false. If that condition is met, then perform a specific action. For instance ...

Drupal 7 FlexSlider - alignment issue with image placement

I am encountering an issue with the Flexslider module on my Drupal 7 website. I have created a simple slider that displays 3 photos. I enabled touch screen functionality for the slider, and everything seems to be working fine except for one problem - all t ...

Designing a personalized carousel component in Angular

Looking to replicate this design, any tips? I'm aiming for a carousel layout with developers listed in a project, where the center item is larger than the others. Any guidance on how to achieve this look? ...

The passport is experiencing an authentication issue: The subclass must override the Strategy#authenticate method

After attempting to authenticate and log in a user, I encountered an error message stating: Strategy#authenticate must be overridden by subclass. How can I resolve this issue? What could be causing this error to occur? Concerning Passport.js const LocalS ...

Achieve perfect vertical alignment for a set of three identical boxes using CSS media queries

Bootstrap is being used and the goal is to align three boxes of the same height vertically. https://i.stack.imgur.com/8xg0g.png Currently, the three blocks are not of equal height and do not occupy maximum space. Some manual padding has been added to addr ...

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...

Saving data from AJAX queries

How can I access and store variables from an ajax request that is returned from a function? While I am able to console.log the variable, I'm having difficulty saving it outside of the scope. This is how it appears: In the HTML: function my_ajax() ...

Unable to extract information from empty <td> using python and selenium

Currently, I am facing an issue while trying to fetch values from a <tr> using Python Selenium. Specifically, I need these values to be ordered and also identified based on whether they contain the word "PICK" or not. My goal is to determine the exa ...

What are effective strategies to stop the generic * { … } style from overriding its parent tag?

How can I prevent my general * { ... } style from overriding the parent tag? In the given scenario, I want the text "sssssssss" to have the style text-huge. .text-huge { font-size: 28px !important; color: green !important; } * { font-size: 12px; ...

Pressing the enter key within Material UI Autocomplete will allow you to quickly create new

Wouldn't it be great if Autocomplete in material ui could do this: wertarbyte Imagine being able to insert text (string) without the need for a list of elements to select from. This means that the noOptions message shouldn't appear, and instead ...

What is the alternative to $templateCache in Angular2 and how can CachedResourceLoader be utilized in its place?

While I have come across 2 similar questions on Stack Overflow and here, none of them seem to provide a solution. After delving into the Angular repository, I stumbled upon this issue where they inquire about an alternative for templateCache in Angular 2, ...

Failed submission: XMLHttpRequest and FormData not processing data correctly

I'm attempting to use AJAX to submit a form using the post method along with a FormData object. Here's a simplified version of the JavaScript code: var form=…; // form element var url=…; // action form['update'].onclick=function ...

The re-rendering of a functional component utilizing React.useCallback and React.memo() is occurring

I was delving into React concepts and eager to experiment with some new things. Here are a few questions that crossed my mind: Does every functional child component re-render when the parent state changes, even if it doesn't have any props? It seems ...

What is the best way to access a database connection throughout an entire node.js application?

In my application's app.js file, I establish a connection to mongodb using the monk module. var express = require('express'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var mong ...

I'm encountering problems when attempting to display the image/png response from an xmlHTTPRequest. Instead of the correct data, I

I have implemented the following code to integrate a captcha generating web service. The response data is successfully obtained, but when I attempt to display the result within a div element, the image appears as distorted text. var xmlHttp = new XMLHtt ...

Creating an object with an array of objects as a field in MongoDB: A step-by-step guide

I have a unique schema here: const UniqueExerciseSchema = new Schema({ exerciseTitle: { type: String }, logSet: [{ weight: { type: Number }, sets: { type: Number }, reps: { type: Number }, }], }); After obtaining the da ...

Check for the presence of a horizontal scrollbar on the page for both computer and mobile devices

Is there a way to determine if a web page has a horizontal scrollbar using jQuery or pure JavaScript? I need this information to dynamically change the css of another element. I initially tried function isHorizontalScrollbarEnabled() { return $(docum ...

Is there a way to prevent duplicate requests in jQuery?

I'm new to using jquery. Can someone please assist me with solving my current task? Here is the code that I have for a form with a select element. It triggers on the onfocus event: function sendBall(id){ $('#bal_'+id).blur(function(){ $.aj ...

Django getJSON with jQuery causing sessionid cookie mismatch

Encountering a problem with getJSON where it is sending an incorrect value for Django's sessionid cookie. There is an API operating on port 8000. When accessing this URL: http://localhost:8000/api/accounts/banner, it returns a JSON document if there ...