The div remains unchanged when the button is clicked

My webpage is filled with several large div elements.

There's a button on the page that, when clicked, should switch to the next div.

Despite my efforts, the code I've written doesn't seem to be working as expected. :(

This is the HTML structure:

<div class="tutorial">
    <p class="heading">Introduce Yourself</p>
    <div class="body">
        <table>
            <tr>
                <td>
                    <label for="full_name">What is your full name?</label>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="text" name="full_name" id="full_name" placeholder="Full Name" />
                </td>
            </tr>
            <tr>
                <td><br/></td>
            </tr>
            <tr>
                <td>
                    <label for="about">Describe yourself:</label>
                </td>
            </tr>
            <tr>
                <td>
                    <textarea id="about" name="about" rows="5" cols="40" placeholder="Share your hobbies, interests, and more about yourself"></textarea>
                </td>
            </tr>
            <tr>
                <td width="900px" height="60px"></td>
                <td>
                    <button id="next" class="btn">Next</button>
                </td>
            </tr>
        </table>
    </div>
</div>
<div class="tutorial hidden">
    <p class="heading">Introduction Continued</p>
    <div class="body">Body</div>
</div>
<div class="tutorial hidden">
    <p class="heading">More about You!</p>
    <div class="body">Body Content</div>
</div>
<div class="tutorial hidden">
    <p class="heading">Let's Explore More!</p>
    <div class="body">Content goes here</div>
</div>
<div class="tutorial hidden">
    <p class="heading">Fascinating Facts About You!</p>
    <div class="body">Interesting Content</div>
</div>

The JavaScript code:

$(function () {
    var tutorials = $("div.tutorial");
    var idNumber = 1;
    tutorials.each(function () {
        $(this).attr("id", idNumber);
        idNumber++;
    });

    var nextButton = $("#next");

    $(nextButton).on('click', function () {
        var currentTutorial = $("div.tutorial").not(".hidden");
        var currentTutorialId = currentTutorial.prop("id");
        currentTutorial.addClass("hidden");
        var nextTutorialId = currentTutorialId + 1;
        var nextDiv = null;
        if ($("div.tutorial").is("#" + nextTutorialId)) {
            nextDiv = $("div.tutorial");
        }
        nextDiv.removeClass("hidden");
    });
});

CSS details have been excluded to keep it concise. :)

Desired Outcome: I aim to have the next button hide the current div and display the subsequent one in sequence.

Actions Taken So Far:

var currentTutorial = $("div.tutorial").not(".hidden");
var currentTutorialId = currentTutorial.prop("id");
currentTutorial.addClass("hidden");
var nextTutorialId = currentTutorialId + 1;
var nextDiv = null;
if ($("div.tutorial").is("#" + nextTutorialId)) {
    nextDiv = $("div.tutorial");
}
nextDiv.removeClass("hidden");

Answer №1

When trying to select by id, it appears that there are no id attributes for the .tutorial divs. However, you can utilize the next jQuery function to access the nextSibling of the current div instead. It is important to ensure that there is at least one div without the .hidden class initially.

For example:

$('div.tutorial:not(.hidden)').addClass('hidden').next().removeClass('hidden');

It is recommended to remove the id from your buttons and opt for using a class, then adjust the selector for the click binding accordingly. As suggested by @koala_dev.

Answer №2

One way to navigate through elements in jQuery is by using the `prev()` and `next()` methods like so:


$(buttonNext).on('click', function () {
    var currentStep = $("div.step").not(".hidden");
    var currentStepId = currentStep.prop("id");
    currentStep.addClass("hidden");

    currentStep.next('div').show();

    nextElement.removeClass("hidden");
});

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

Arranging React Grid Items with Stylish Overlapping Layout

Is there a way to create a react-grid-layout with 100 grid points width, while ensuring that the grid items do not overlap? https://i.sstatic.net/CQiVh.png (Reducing the number of columns can prevent overlap, but sacrifices the 100-point width resolution ...

What is the best way to ensure that a div appears below, rather than alongside, another one

I need help positioning my divs on the webpage. Currently, my map div is appearing next to the list instead of below it. The height of the list can vary as it is generated dynamically. I want the map div to be on the right side with the list displayed on t ...

Automatic scrolling feature in JavaFX

I am currently working on developing a chat box using JavaFX. My goal is to implement an auto-scroll feature that will scroll down the page when it gets filled up. However, I am facing some issues with this functionality. import javafx.application.Applica ...

Acquire a portion of a string with JavaScript or jQuery

Given the string testserver\sho007, how can I utilize jQuery to extract only the value sho007? ...

Target the most recently loaded Vue.js element using jQuery's focus method

Hey there, I am currently utilizing Vue.js to load some data and below is the code snippet: add_line:function() { index = this.lines.length; this.lines.push({id:index}); $('.search_and_select').last().focus(); ...

Stop event bubbling in Vue.js for router link

I'm working with the following HTML template... <template> <li class="nav-item" style="z-index:9"> <router-link :to="link.path" @click.native="linkClick" ...

URL not functioning properly on Django CMS menu

After setting up django-cms and creating a collapsible menu with categories and subcategories, I encountered an issue. When clicking on a main category, the URL appears correct but it does not navigate to the corresponding page. Main categories without chi ...

Issue with pagination functionality post-Ajax request on Rails platform

I am working on implementing pagination using the Kaminari plugin. As I Ajaxify my application, I have run into an issue. I have a form that contains paginated data along with another form used for filtering that data (both work via Ajax). Initially, the p ...

Connecting Laravel with Express Js

Greetings, I have a technical inquiry. I am proficient in Laravel but relatively new to Express Node. Currently, my code is functioning well with jQuery, but I need to convert it to Express. Should I install Express in the same folder as my Laravel project ...

Guide on utilizing the carousel component in Bootstrap and populating it with data generated from Node.js

My goal is to design a carousel that displays 5 different pieces of information pulled from a separate app.js file. I attempted to implement a forEach loop, but encountered issues when trying to create a second Bootstrap carousel container. Here's th ...

Tips on invoking a class method within lodash debounce function

Help needed: Issue with TypeError - Expected a function at debounce when calling a class method in the lodash debounce class Foo { bar() { console.log('bar'); } } const foo = new Foo(); _.debounce = debounce(foo.bar(), 300); ...

Identifier for md-radio-group

In my Angular 4 Material application, I have a set of radio buttons grouped together: <md-radio-group fxLayout fxLayoutAlign="center center" fxLayoutGap="30px"> <md-radio-button value="1">Date</md-radio-button> <md-radio-butto ...

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...

The body content of the webpage needs to be updated without altering the header and footer, all while avoiding a page

On my website, I have a header menu that includes buttons for "home" and "about us." The default page is set to the home page. Within the home page, there is a specific link. When this link on the home page or the "about us" button is clicked, I want the ...

Latest news on KnockoutJS enhancements

Is there a way to create an HTML markup with a GIF progress bar that appears when the page is loading? I want to use Ajax to fetch data, populate the markup, and then hide the GIF. How can I achieve this functionality using KnockoutJS? var Item = functi ...

How to populate an ExtJS 3.4 combobox with local JSON data in a few simple steps

I am utilizing ExtJS 3.4 and in need of populating a combobox with specific data obtained from a previous XMLHttpRequest, stored in a variable as follows: my_variable = "[{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","no ...

tips for remaining in modal window post form submission

I have a form within a modal window. I am using ajax to load content in the same modal window, but the issue is that it redirects to the main page after submitting the form. How can I ensure that the modal window stays open even after the form submission? ...

Is it possible for (variable or {}) to function seamlessly across all web browsers when using Javascript

When writing code in JavaScript, the if(variable) clause is used to check if a list or array is not null or undefined in order to avoid exceptions. Here's an example: if (list) for (var k in list) { ... if (array) for (var i = array.l ...

Partial implementation of jQuery datepicker feature facing technical issues

Greetings, I have a functional datepicker implemented in my code as follows: <link rel="stylesheet" href="uidatepicker/themes/blitzer/jquery.ui.all.css"> <script src="uidatepicker/jquery-1.5.1.js"></script> <script src="uidate ...

Encountering ECONNREFUSED error when making requests to an external API in a NextJS application integrated with Auth

Currently, I have integrated Auth0 authentication into my NextJS application by following their documentation. Now, I am in the process of calling an external ExpressJS application using the guidelines provided here: https://github.com/auth0/nextjs-auth0/b ...