The div element makes a comeback following its disappearance using the .hide() method in jQuery

I've tried various solutions and checked similar questions, but I have had no luck so far.

I have a simple div where users can enter their name and surname. My goal is to post the input to another page using jQuery, hide the first div (div1), and show the second div (div2) to ask a question (which is initially hidden).

However, when I submit the form, the data is successfully posted and stored in the database. But, after an alert, div1 reappears and div2 disappears. Can someone please assist me with this issue?

Thank you so much!

Below is the jQuery code:

    <script>
        function saveDetailsToDB()
        {

            var name = document.getElementById('name').value;
            var surname = document.getElementById('surname').value;

            if (name === "" && surname === "") 
            {
                alert("Please enter your details!");
                $("#UQ").css( "display", "none");   

            }

            else if(name !== "" && surname === "")
            {
                alert("Please enter your Surname");
                $("#UQ").css( "display", "none");

            }

            else if(name === "" && surname !== "")
            {
                alert("Please enter your Name");
                $("#UQ").css( "display", "none");
            }
            else
            {

                $.post("saveDetails.php",{ name: name,surname: surname });
                $("#detailsDiv").hide();
                $("#UQ").show();
                alert('You have been successfully registered!');

            }   
        }
    </script>

Here is the HTML code:

    <div id = "detailsDiv">
        <form>
            <b><label>Name:</label></b><br> 
            <input type = "text" id = "name"><br><br>

            <b><label>Surname:</label></b><br>
            <input type = "text" id = "surname"><br><br>
            <button onclick="saveDetailsToDB();">Send</button>
        </form>

    </div>

    <div id = "UQ">
    <b><label>Please enter your question.</label></b><br><br>
    <form>
        <textarea id = "question" rows="4" cols="40"></textarea><br><br>
        <button onclick="saveQuestionToDB()">Save</button>
    </form>
</div>

Answer №1

The problem arises because the default action of the button click is not prevented, causing the page to reload and giving the illusion that the content is reappearing. Here's a solution to fix this issue:

<button onclick="saveDetailsToDB(); return false;">Send</button>

Even better, you can remove the outdated onclick attribute from your HTML and use JavaScript to attach the events:

<button class="btn-save">Send</button>
$(function() {
    $('.btn-save').click(function(e) {
        e.preventDefault();

        var name = $('#name').val();
        var surname = $('#surname').val();

        if (name === "" && surname === "") {
            alert("Please, enter your details!");
            $("#UQ").hide();
        }
        else if(name !== "" && surname === "") {
            alert("Please, enter your Surname");
            $("#UQ").hide();
        }
        else if(name === "" && surname !== "") {
            alert("Please, enter your Name");
            $("#UQ").hide();
        }
        else {
            $.post("saveDetails.php", { 
                name: name,
                surname: surname 
            });
            $("#detailsDiv").hide();
            $("#UQ").show();
            alert('You have been successfully registered!');
        }   
    });
});

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

How can I display a JSON object as a table in Sinatra?

When working with Sinatra, an Ajax action returns a JSON object. I am trying to display this data in a table within my view. The JSON object includes a list of items that need to be shown. One approach is to render the table using JavaScript. This would i ...

What causes Next.JS to automatically strip out CSS during the production build process?

Encountering unpredictability in CSS loading while deploying my Next.JS site. Everything appears fine locally, but once deployed, the CSS rules seem to vanish entirely. The element has the attached class, yet the corresponding styling rules are nowhere to ...

Trigger an alert after a separate function is completed with jQuery

On my page, I have a function that changes the color of an element. I want to trigger an alert once this action is complete using changecolor(). However, I am unable to modify the changecolor() function due to certain restrictions. Is there a way to dete ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

The getElementById method in JavaScript can result in a null return value

Why is null returned by the getElementById method in JavaScript? <html> <head> <title>test_elementObject</title> <script language="JavaScript" type="text/javascript"> <!-- var input1 = document.getElementById ( " ...

What could be causing the absence of the margin in my code?

I am currently working on a website layout where I want to display an image with some information below it, and the information should have a colored background with some margin around it. However, when I try to view the code I have written, the margin i ...

Lock GridView headers when only scrolling vertically

I am facing an issue with my gridview on an aspx page. The gridview is wider than the page itself, so I want the headers of the gridview to scroll horizontally along with the content, while remaining fixed vertically. Can anyone help me achieve this? I hav ...

The issue lies in the error code TS2315 which states that the type 'observable' is not a generic

I keep encountering an error message that says 'observable is not generic' while importing files. I am working on implementing CRUD operations in Angular 7, where I have created two components for adding and listing employees. The functions for c ...

Attention: validation of DOM nesting encountered an error: element <div> is not permitted to be nested inside <p>

I am facing the issue of not being able to find a solution to a known problem. The paragraph in question must not contain any other tags, yet I did not use any paragraph tags in my case. return ( <div className={classes.root}> <Stepper acti ...

Encountering a challenge while attempting to adjust the navigation bar at the top as the user scrolls through the page

I've been working on making the navigation bar stay fixed at the top of the page when the user scrolls, but I'm running into some issues. It seems that certain elements are overlapping the navigation bar, causing them to hide the navigation bar a ...

error: unexpected token } in Node.js syntax

I am struggling to identify my issue! /var/www/html/bot# nodejs driver /var/www/html/bot/driver.js:2239 }); ^ SyntaxError: Unexpected token } at createScript (vm.js:80:10) at Object.runInThisContext (vm.js:139:10) at Module._co ...

Creating unique div elements with varying sizes that perfectly complement each other

I'm interested in creating a grid of divs that are randomly filled, similar to the image shown. I want them to be completed in a unique way without overlapping with each other. Is there a method to achieve this? ...

Tips for generating multiple URL destinations within a single hyperlink

I am looking to create a unique feature in HTML where multiple tabs can be opened with different URLs using one link. While I know how to open one link in a new tab, I am unsure of how to simultaneously add another URL that will open up in a separate tab ...

The combination of several JOIN operations and GROUP BY is leading to unexpected results with the ORDER BY clause

SELECT msg.msgFrom, mem.memberID, mem.memberFirstName, mem.memberLastName, msg.msgJobID, msg.msgMessage, msg.msgRead, job.jobDescription FROM messages msg JOIN members mem ON msg.msgFrom = mem.memberID JO ...

Adjust the button's hue upon clicking it

The current function is operational. Upon pressing the button, it toggles between displaying "click me" and "click me again". However, I desire the button to appear blue when showing "click me" and red when displaying "click me again". <!DOCTYPE html ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

degree of transparency when semi-transparent elements overlap

Imagine you have two <div> elements, one with an opacity of .5 and another overlaying it with the same opacity. What would be the combined opacity of the two? Interestingly, it's not as simple as, .5 × .5 or even, .5 + .5 How can this ...

Ensure the slider functions on all types of browsers

I found a code snippet for an image slider on codepen and integrated it into my project. However, I encountered some issues trying to center the slider in the browser window with 5% space on each side. I attempted using $(window).width(); to set the width ...

The Enigma of AngularJS Coding

Check out this code snippet. $scope.$watch('year', reloadData); $scope.$watch('month', reloadData); $scope.year = 2017; $scope.month = 1; var reloadData = function() { /* Refresh Data */ } var init = function() { $scope.year ...

Updating the innerHTML of a frameset

I have a unique challenge that involves loading the frameset of www.example.com/2.html when accessing www.example.com/en/test/page.html. Successfully accomplished this task. Now, after loading 2.html in the frameset, I want to modify ".html" to ".html" t ...