Changing divs using JavaScript in an ASP.NET MVC application

I am making an AJAX request to retrieve Question1-Question10 from the back-end

Below is the code for the request:

<script>
$(document).ready(function() {
    question_block();
});

function question_block() {
   $.ajax({
        url: '@Url.Action("QuestionBlocks", "Interwier")',
        contentType: 'application/json; charset=utf-8',
        type: 'GET',
        dataType: 'json',
        processData: false,
        success: function(result) {
            var email = result;
            for (var i = 0; i <= email.length - 1; i++) {
                var question = '<div style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question1 + '</div>'+
                '<div style="font-size:20px;">' + email[i].Question2 + '</div>' +
                    '<div style="font-size:20px;">' + email[i].Question3 + '</div>' +
                    '<div style="font-size:20px;">' + email[i].Question4 + '</div>' +
                    '<div style="font-size:20px;">' + email[i].Question5 + '</div>' +
                    '<div style="font-size:20px;">' + email[i].Question6 + '</div>' +
                    '<div style="font-size:20px;">' + email[i].Question7 + '</div>' +
                    '<div style="font-size:20px;">' + email[i].Question8 + '</div>' +
                    '<div style="font-size:20px;">' + email[i].Question9 + '</div>' +
                    '<div style="font-size:20px;">' + email[i].Question10 + '</div>';
                $("#questions").append(question);
            }
        },
        error: function() {
            alert("Something went wrong in the controller");
        }
    });
}

I want to display the first div by default and when a button, for example next, is clicked, I want to hide the first div and show the second one, and so on.

How can I achieve this?

Answer №1

        <script>
$(document).ready(function() {
    displayQuestions();
});

function displayQuestions() {
   $.ajax({
        url: '@Url.Action("QuestionBlocks", "Interwier")',
        contentType: 'application/json; charset=utf-8',
        type: 'GET',
        dataType: 'json',
        processData: false,
        success: function(result) {
            var questions = result;
            for (var i = 0; i <= questions.length - 1; i++) {
                var display = '<div style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + questions[i].Question1 + '</div>'+
                '<div style="font-size:20px;">' + questions[i].Question2 + '</div>' +
                    '<div style="font-size:20px;" class="que show'">' + questions[i].Question3 + '</div>' +
                    '<div style="font-size:20px;" class="que hide">' + questions[i].Question4 + '</div>' +
                    '<div style="font-size:20px;" class="que hide">' + questions[i].Question5 + '</div>' +
                    '<div style="font-size:20px;" class="que hide">' + questions[i].Question6 + '</div>' +
                    '<div style="font-size:20px;" class="que hide">' + questions[i].Question7 + '</div>' +
                    '<div style="font-size:20px;" class="que hide">' + questions[i].Question8 + '</div>' +
                    '<div style="font-size:20px;" class="que hide">' + questions[i].Question9 + '</div>' +
                    '<div style="font-size:20px;" class="que hide">' + questions[i].Question10 + '</div>';
                $("#questions").append(display);
            }
        },
        error: function() {
            alert("There was an issue with the controller");
        }
    });
}


// click on next
function moveNext(){
    $(".que").each(function(){
        if( $( this ).hasClass('show') ){
         $( this ).removeClass("show").addClass('hide');
         $( this ).next().removeClass("hide").addClass('show');
      } 
  });
}
// Similarly, you can implement the back button functionality

Answer №2

Utilize two classes called "activeQue" and "hiddenQue"

By default, assign the "activeQue" class to the first question and give the rest the "hiddenQue" class.

Then, you can implement code like the following on a next button to toggle between showing and hiding questions:

var element = $(".activeQue");
$(element).removeClass("activeQue").addClass("hiddenQue");
$(element).next().addClass("activeQue");

It should function similar to this example.

Answer №3

To achieve this effect, you can set the second div to have style="display:none" by default. Then, when clicked, you can hide the first div and show the second div using the following jQuery code:

$("#first").slideUp();
$("#second").slideDown();

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

I'm having trouble with my react-big-calendar not updating when I switch between day, month, or week views -

Why won't my calendar change to the week view when I click on that section? https://i.stack.imgur.com/gh2aO.png In the screenshot above, my default view is set to month, but when I attempt to switch to week, it only highlights the option without cha ...

What are the steps to execute a filter operation on a table by utilizing two select box values with jQuery?

I have a challenge with two dropdown menus. One contains names and the other subjects, along with a table displaying information in three columns: name, subject, and marks. I would like to implement a filter based on the selections in these two dropdowns. ...

Inadequate speed and efficiency in Javascript and JQuery operations

I'm facing severe lag problems in my JavaScript code, particularly with the parallax effects being very slow. I suspect this is due to multiple executions of functions. Below is the code snippet: function tada() { $(".arrow").addClass("tada"); s ...

Modifying the timing in a .SRT file by adjusting seconds

I have scoured the web and found no similar solution. My goal is to develop a simple PHP/js/jq script that can adjust the timing of an .srt file by adding or subtracting seconds. I am unsure whether using regex would be the best approach for this task or ...

Exploring NextJS with Typescript to utilize the getStaticProps method

I'm currently enrolled in a NextJS course and I am interested in using Typescript. While browsing through a GitHub discussion forum, I came across an issue that I don't quite understand. The first function provided below seems to be throwing an e ...

"Troubleshooting: Inability to send emails through PHP mail script while using jQuery's

I'm at a loss with this issue. I'm attempting to utilize the jQuery ajax function to send POST data to an email script. Below is the jQuery code snippet. $('#bas-submit-button').click(function () { var baslogo = $('input#bas- ...

Creating personalized components - a step-by-step guide

I'm looking to customize the appearance of the snackbar background, buttons, and other elements in my Material UI project. As a newcomer to Material UI, I'm unsure if I'm taking the correct approach with this code snippet: const styles = { ...

Unable to implement multiple draggable inner objects using Angular 5 and dragula library

After struggling for the past few days, I can't seem to get it to work... Here is a brief explanation of my issue: In this example, I have an array of objects structured like this: public containers: Array<object> = [ { "name": "contain ...

Is it feasible to restrict access to specific fields of an object in the Firebase database for viewing purposes using Firebase permissions?

Consider this JSON structure representing a Firebase DB: { "users": { "user0": { "name": "Mike", "age": 20, "relationship": "married", "friends": [...] }, "user1": { " ...

Exploring the Distinctions Among Express Router, Module Export, and App.Use() in Node and ExpressJS

I am working with app.js, where the code looks like this: var express = require('express'); var report = require('./routes/Report'); var app = express(); app.use('/api/appReport', report); app.listen(3000); module.exports ...

Element.style prevents customization of Rev Slider dimensions

I'm currently attempting to adjust the height of my rev slider from 100% to 80%, but I can't seem to locate the necessary code. Upon inspecting in Chrome, I noticed the following: element.style { max-height: 1080px; margin-to ...

Choose the url path using UI-Router option

In my Angular project, I am implementing a complex structure of nested states using UI-Router. I am working on setting up a parent state that will determine the language of the application based on an optional locale path in the URL. For Spanish www.web ...

Mini-navigation bar scrolling

I am trying to create a menu where I want to hide elements if the length of either class a or class b is larger than the entire container. I want to achieve a similar effect to what Facebook has. How can I make this happen? I have thought about one approac ...

"Implementation of Google+ button causing the appearance of a horizontal scrollbar

Adding Facebook and Twitter sharing buttons was easy, but now I'm having trouble with Google+. No matter where I place the code on my page (using a Bootstrap grid), it always adds 2-3 pixels on the right side, creating a horizontal scrollbar: <div ...

What is the process for changing the URL displayed in the address bar for each individual page?

Hey everyone, I need some help with a website issue I'm having. Let me explain what I'm trying to accomplish. My website www.website.com has several pages and is currently hosted on Apache via Aruba www.website.com/site/index.php ...

How can I update the color scheme in styled components based on the active state of the component?

I'm currently working on a react accordion component that requires changing styles based on the active and inactive states. I have successfully set the state and added two props for color and active color. The goal is to change colors when the user cl ...

The URIError occurred while attempting to decode the parameter '/December%2015,%' within the express framework

After setting up a middleware using the express framework that handles a URI with a date as a parameter, I encountered a small issue. app.get("/:date",function(req,res){ var result; var myDate=req.params.date if(moment(myDate).isValid()) ...

Error encountered in ASP.NET: Unsupported keyword 'data source' in the query

Just a bit of context: I'm currently following a tutorial for an ASP.NET site, you can find it here. Working in Visual Studio 2012. The only changes made were the namespace names, other than that, followed everything as instructed. Encountering thi ...

What is the best way to ensure only one checkbox is checked at a time and have it automatically uncheck when another checkbox is selected?

Is there a way to make a checkbox automatically uncheck when another one is checked? For example, when checkbox one is clicked, it should be marked as checked and any other checkboxes should be marked as unchecked. The same behavior should apply when check ...

Troubleshooting problem with CSS background image

I'm looking to make my webpage more dynamic and interactive. One issue I have is that the background image of the body element stretches when new elements are added, which is not the desired behavior. Any suggestions on how I can fix this? <styl ...