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

Error message "Undefined error encountered when attempting to display an array of objects using jQuery and PHP through AJAX on the console"

While trying to parse a JSON using jQuery and AJAX, I encountered an issue where some objects in the Array, like the SUM(amountbet) object, are showing up as "undefined" in the console. The image above depicts the SUM(amountbet) object appearing ...

differentiating between user click and jquery's .click() method

There are <a href=".. tags on a page with an inline onclick attribute. If a user clicks one without being logged in, they will be prompted to log in. After logging in and the page refreshes, jQuery will trigger .click() on the <a> element to redir ...

Is there a way to retrieve just one specific field from a Firestore query instead of fetching all fields?

I am experiencing an issue where I can successfully output all fields in the console, but I only want to display one specific field. In this case, I am trying to retrieve the ID field but I am encountering difficulties. Below are screenshots illustrating m ...

What is the best way to transform React API data into props that can be utilized in different components?

I've been struggling with this issue for quite some time now, unable to understand how to manipulate the data in a way that allows me to use it in other components. Although I can display the data correctly, I'm advised to structure it within a f ...

The TypeScript Promise error codes TS2304 and TS2529 are causing confusion among

I came across the code below: function asyncTask(): Promise<string> { return new Promise<string>(resolve => resolve); } This code resulted in the following error: TS2304: cannot find name 'Promise' To address this issue, ...

Include a hyperlink to a website that was created with the help of Photoshop

Is it feasible to incorporate a hyperlink into a website that was designed using Photoshop templates? In the past, creating templates in Photoshop and then adding links with tools like Dreamweaver was common practice. I believed that dynamically adding li ...

Can you eliminate the commas and turn it into a string?

function EncryptMessage(message) { var encryptedArr = []; for(i=0;i<message.length+1;i++){ var unicode = message.charCodeAt(i); var encryptedUnicode; var newCharacter = String.fromCharCode(encryptedUnicode); if( ...

How can I utilize jQuery-ajax to call a Struts2 action within WebSphere Portal 6.1?

Hi there, I'm trying to call a struts2 action using jQuery ajax. So far, I've only been able to call a Servlet using ajax. Can anyone help me out with this issue? Here's the code I have: This is my struts.xml file: <?xml version="1.0 ...

I encountered a SyntaxError that reads "Unexpected token instanceof" while using the Chrome Javascript console

I find it quite surprising that the code below, when entered into the Chrome JavaScript console: {} instanceof Object leads to the error message displayed below: Uncaught SyntaxError: Unexpected token instanceof Could someone kindly explain why this ...

Can you please guide me on how to convert pug (jade) to html using npm scripts?

Struggling to construct my package.json file, I find myself facing a challenge when it comes to writing scripts. "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build-css":"node-sass --output-style compressed -o bu ...

Tips for inheriting external UI components in vue/nuxt?

Hello, I am currently navigating the world of Vue for the first time. My project utilizes Vue2, Nuxt, and Vuetify to bring it all together. One thing I am looking to do is create a base .vue component, as well as multiple components that inherit from this ...

Create a data attribute object and assign to it the prop object received from the parent component

I am struggling with passing an object as a prop from a parent component and then utilizing it to initialize the child component with the received value. The main objective behind this is to create a dialog box that includes a child form component with mu ...

Several different factors

I need to develop a form that allows users to edit existing comments. The form will display a textarea containing the old comment text and a submit button. My goal is to send the newComment data via ajax to another script. However, I am facing an issue w ...

Having trouble selecting a dynamically changing div element in Selenium with Java using a click action

Every time I navigate to www.reddit.com and enter a query in the Search field, then press enter to go to the first valid link within a subreddit, sorting options are presented. By default, it is set to BEST but I wish to change it to TOP. My test class cod ...

Leverage the power of ImageMagick and Uploadcare to effortlessly showcase thumbnails for PSD and PDF file formats

I have implemented a form on my website where users can upload files using an Uploadcare widget. The widget allows users to preview the uploaded images in formats like jpg and png, but I am looking for a way to also display previews for other file types su ...

Mastering React hooks: A guide to effectively updating and rendering elements

Each time I click the delete button, it seems to only remove the last element instead of the specific one based on index. Is there a better way to achieve this without changing from <input defaultValue={name} /> to <input value={name} /> in t ...

Is the main content positioned below the sidebar on smaller screens?

In order to achieve a 250px col-2 sidebar with a col-10 main body that collapses into a top navbar and main content beneath it, my goal is set. However, I am facing an issue where the main content body goes underneath the sidebar when the screen size cha ...

Showing the loading screen while waiting for the static Next.js app to load

Looking for a way to implement a loading screen right before the entire static page finishes loading? I'm currently utilizing modules:export to create my static page, but struggling to listen to the window load event since NextJs has already loaded th ...

Error message "Exceeded the maximum call stack size" encountered during Vue-router authentication

I am currently in the process of developing a dashboard using Vue, Vuex, and Quasar. However, I have encountered an authentication error that is preventing me from progressing. Additionally, I need assistance in ensuring that when a user is already logged ...

Exploring JSON data with ReactJS

I am experiencing issues with populating a table with data imported from a JSON file. The error message I'm receiving is: Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {list}). If you intended to render ...