Switching back and forth between JQuery and CSS display changes

My challenge involves utilizing a JQuery file to present one question at a time in a quiz format. Upon clicking the submit button, the intention is to progress to the subsequent question. However, I have encountered an issue where the transition occurs momentarily upon button press before reverting back to the initial question.

The code snippet I am working with is outlined below:

$(document).ready(function() {
"use strict";
// jQuery logic for each question
$('button#FlexibilityNext01').click(function() {
$('#FlexibilityQ01').css({'display':'none'});
$('#FlexibilityQ02').css({'display':'block'});
});

// Similar logic for Questions 02 through 09

// Handling final question and retake option
$('button#FlexibilityFinishQuiz').click(function() {
$('#FlexibilityQ10').css({'display':'none'});
$('#RetakeQuiz').css({'display':'block'});
});

$('#FlexibilityRetakeQuiz').click(function() {
$('#FlexibilityRetakeQuiz').css({'display':'none'});
$('#FlexibilityQ01').css({'display':'block'});
});

});
<div class="Question" id="FlexibilityQ01">
      <form id="FlexibilityFormQ01"> 
        <!-- form question here -->
      <button type="submit" id="FlexibilityNext01">Next Question</button>
      </form>
</div>  <!-- class="Question" id="Q1" -->

<!-- HTML markup for questions 02-10 follows similar structure -->

I have attempted various display manipulation methods such as hiding/showing elements and changing CSS properties using both `$('#id')` and `$("#id")`, but all seem to manifest the same issue.

Answer №1

When you use submit buttons, you are instructing the page to send the form when the button is clicked. If no action is specified for the form, it will default to the current page. So, each time a submit button is clicked, the click event is triggered, and your bound handler executes, revealing the next question. However, it then submits the form to itself, causing the page to reload. The reloaded page does not retain the previous state before the form was submitted, so it displays the initial state (the first question) again.

From the code provided, there seems to be no need for the buttons to be of type submit. Unless there is a reason not shown in this code, you can simply change them to type="button", which will solve the issue. This change would also allow you to remove all the <form> elements.

Answer №2

If you have all the questions visible on your page and want to show/hide them, it would be more efficient to use links like <a href="#" class="next"> instead of forms/buttons for navigation. You can simply have two links - one for moving to the next question and another for going back to the previous one, while keeping track of the current position in a variable. Check out an example like this.

In any case, a quick solution here is to prevent form submission using $.preventDefault().

$('_selector_').click(function(e) {
    e.preventDefault();
    $('_selector_').css({'display':'none'});
    $('_selector_').css({'display':'block'});
});

Answer №3

Considering your mention of needing to send this view to the server, I will provide an answer that covers that aspect as well. It would have been helpful if you had included this in your original question.

It is important to have a good understanding of how event handlers function in both JavaScript and jQuery. Different elements trigger various events apart from just click, so it is crucial to understand the default behavior of different types of elements in the browser. For instance, the default action of a "submit" button is to POST the form back to the page, but it can easily be disabled.

I've optimized your code to make it more concise yet still effective - a bit more complex, but easier to maintain overall :)

$(document).ready(function() {

  var currentQuestion = 1

  // ignore form submits
  $('.Question form').on('submit', function(e) {
    e.preventDefault() 
  })


  // Iterate through all the questions
  $('.Question').each(function(i, qEl) {
    var question = $(qEl)

    // Trigger the next function when 'submit' button is clicked
    // You could enhance readability by adding classes to the buttons.
    question.find('button[type="submit"]').on('click', next);

    // Do the same for previous
    question.find('button[type="button"]').on('click', prev);

    function next() {
      // Increase the question counter by 1. Note that the current question
      // variable is *outside* of this `closure`. Look up that term for more information.
      currentQuestion++

      // If the counter exceeds the total number of questions we have,
      // set it back to 10
      if (currentQuestion > 10) {
        currentQuestion = 10
      }

      updateQuestions()
      // Here, we could send the form state to the server and wait for the response before displaying the next question.
      // $.ajax({
      //   type: 'post',
      //   url: location.pathname,
      //   data: question.find('form').serialize()
      // }).then(updateQuestions)
    }

    // Similar to next but in reverse direction.
    function prev() {
      currentQuestion--
      if (currentQuestion < 1) {
        currentQuestion = 1
      }
      updateQuestions()
    }

  })

  // Loop through all the questions and display only the active one based on the currentQuestion variable.
  function updateQuestions() {
    $('.Question').each(function(i, qEl) {
      var question = $(qEl)
      var id = question.attr('id')

      // Extract and convert '01' into a numeric value.
      var num = parseInt(id.replace('FlexibilityQ', ''), 10)
      if (num === currentQuestion) {
        question.show()
      } else {
        question.hide()
      }

      // Special logic for handling the finish stage
      // if (num === 10) { doSomethingSpecial() }
    })
  }

})

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

PHP-powered webcasting platform

I have a client who is looking for a website that can live stream uploaded videos through search functionality. One of their main requests is to cover and record certain weekly events on camera, with the video being visible live on the website. While I am ...

Issues with Firefox's flexbox functionality are preventing it from working

Hey there, I've created a bubble menu with a button using code. It functions perfectly on Chrome but seems to have some issues on Mozilla Firefox. You can check it out and give it a try. $(".roundedBallOuter").click(function(e) { $(this).toggleCl ...

Can we find a method to incorporate multicolored borders?

I currently have a td element with the following CSS styling: td { border-bottom: 3px solid aqua; } I want to be able to click on these cells and change their color, similar to the images linked below: https://i.sstatic.net/5DscU.png Is there a way ...

The Vue2 @click event does not function properly when using v-html within a different component

I currently have a sign up form that includes an Alert component for displaying any errors. One of the conditions may prompt a message saying "You already have an account, click here to log in". The error messages are passed as props to the "Alert" compon ...

The use of non-breaking space symbol ( ) does not function properly in Weblogic 14

After upgrading from Weblogic 12 to Weblogic 14 Server, I encountered a change in behavior. Previous Status Everything was functioning properly before the update. When requesting an html page with &nbsp; whitespaces, the server would include these spa ...

How can I insert mock data into a datatable using Django?

I recently completed a small application using django. In order to implement datatables, I used the code from django_datatables_view.base_datatable_view import BaseDatatableView import. This datatable displays results directly from the queryset. I now h ...

Invoke a function in Angular when the value of a textarea is altered using JavaScript

Currently, I am working with angular and need to trigger my function codeInputChanged() each time the content of a textarea is modified either manually or programmatically using JavaScript. This is how my HTML for the textarea appears: <textarea class ...

Execute code after selecting the link

To simplify my question, I will provide an example: Suppose I have two sample pages that I want to demonstrate: Page 01 <script> var demo = 'X1'; alert(demo); $( document ).ready(function() { $("#cont").on("click" ...

Tips for dynamically changing the content of a child div element after a successful ajax call using PHP

I am facing an issue where all the child divs are getting updated on ajax success instead of just the specific one I want to update. Here is my HTML: <div class="add_wishlist"> <input type="hidden" name="prd_wishlist" ...

Struggling with establishing a connection between Jquery and a .php file

I've encountered an issue with my jquery code. I'm uncertain if it's correctly connecting to doc.php as nothing is getting inserted into the database. In doc.php, I have an insert command that I know is functioning properly. My goal is to ...

Query: How can I retrieve the value of a td element in a dynamic table?

Below is an example of how the table will be structured: <tr class="A" id="A${a.index}"> //id will be generic such as 1,2,3,4,5 <table id="mytable"> <tr> <td>a</td> <td>b</td> ...

What are the various ways to send data using Ajax to multiple elements?

script.js $(document).on("click", ".send", function (event) { $.ajax({ url: "update.php", data: { id: id, }, type: "POST", success: function (da ...

Vue's smooth scrolling in Nuxt.js was not defined due to an error with the Window

There seems to be an issue with adding vue smooth scroll to my nuxt.js project as I'm encountering the "window is not defined error". The steps I followed were: yarn add vue2-smooth-scroll Within the vue file, I included: import Vue from 'vue ...

Using Javascript to dynamically enable or disable an input field depending on the choice made in another field

I attempted to implement the solution provided in this answer for my code: How do I disable input field when certain select list value is picked but unfortunately, it is not working as expected. The scenario involves an HTML select field with the ID &apos ...

Having trouble compiling your Vue project and running into the "No mixed spaces and tabs" error?

Below are the details with an error: Error Details: Failed to compile. ./src/components/Header.vue Module Error (from ./node_modules/eslint-loader/index.js): H:\project\VueProjects\stock-trader\src\components\Header.vue 27: ...

What is the best way to rearrange the elements in a database after they have been displayed?

I have a feature on my website where you can enter text into a textbox and then click a button to save it in a database. The saved entries are displayed along with buttons for deleting an entry and moving it to the top of the list. <?php $resultset2 = ...

Transfer files and data efficiently using Ajax

I am facing an issue while trying to send a file and data together to the Controller. When I only send the file, it works correctly. However, when attempting to send both data and a file, nothing seems to work. contentType: false, processData: false, Rem ...

Issue with the div elements not aligning next to each other

I am facing an issue with my code in blade.php where I need to display images. The ideal layout would be to have the images stacked side by side within a div element, but unfortunately, it's not working as expected. I have tried using flex, bootstrap ...

"Utilizing node.js to create a custom regular expression for removing anchor tags

Can someone provide me with a regex pattern that can eliminate all the a tags from HTML and display the URL as plain text? For instance, take this text: abc <a href="http://a.com" target="_blank">bbb</a> ccccccc After applying the regex patt ...

Displaying dynamic data in a Bootstrap modal using Laravel

I have implemented a bootstrap modal in my dashboard. The button that triggers the modal is placed on another page where I extend the dashboard layout. When I click on a button with a different product ID, I want the modal to display information related ...