Guide to ensuring modal box only appears once all criteria are satisfied

On my website, I have a form that requests the user's personal information. After filling out the form, a modal pops up with a "Thank you for signing up" message. The issue is that even if all fields are left blank and the button is clicked, the modal still appears. How can I make the modal appear only after all fields are completed?

I also need the user's input to remain on the page after clicking the button, but changing the button type from submit to button causes all input fields to clear as soon as the last question is answered.

If anyone has suggestions or solutions, it would be greatly appreciated!

Below is the form:

<form id="personalinfo" name="personalinfo" onsubmit="ask()">
    <b>Please sign up with us before you proceed:</b><br>
    First Name: <input name="firstname" required="" size="40" type="text"><br>
    <br>
    Last Name: <input name="lastname" required="" size="40" type="text"><br>
    <br>
    Age: <select name="dropdown">
        <option value="1">10-18</option>
        <option value="2">19-25</option>
        <option value="3">26-35</option>
        <option value="4">36-45</option>
        <option value="5">46-55</option>
        <option value="6">56-65</option>
        <option value="6">65+</option>
    </select><br>
    <br>
    Gender: <input name="gender" required="" type="radio" value="male"> Male<br>
    <input name="gender" required="" type="radio" value="female"> Female<br>
    <input name="gender" required="" type="radio" value="other"> Other<br>
    <br>
    <br>
    <button id="OK!">OK!</button>
</form>

<div id="myModal" class="modal" type="button">
    <div class="modal-content">
        <span class="close">&times;</span>
        <p>Thank you for signing up with us ! You can now proceed to the test.</p>
    </div>
</div>

<script>
    var modal = document.getElementById('myModal');
    var btn = document.getElementById("OK!");
    var span = document.getElementsByClassName("close")[0];

    btn.onclick = function() 
    {
        modal.style.display = "block";
    }

    span.onclick = function() 
    {
        modal.style.display = "none";
    }

    window.onclick = function(event) 
    {
        if (event.target == modal) 
        {
            modal.style.display = "none";
        }
    }

</script>
</form>

Answer №1

One of the reasons why your form is being cleared is because it gets submitted to the server, causing the page to reload with an empty form.

To address this issue, there are two possible approaches you could take:

  1. Traditional form submission
  2. AJAX form submission

In the first scenario, you would send the form data, process it on the server, and then redirect to a new page displaying a welcome message (similar to the content in your modal). However, the drawback here is that your form would be cleared upon submission.

In the second scenario, you need to follow these steps in order:

  • Send the form data to the server using AJAX
  • Handle both success and error cases appropriately
  • Show your modal with a message based on the result (success or error)

For making changes in your code, in the HTML section:

  1. Remove onsubmit="ask()" from the <form> tag
  2. Add a type="submit" attribute to your submit button
  3. Add style="display:none" to your <div id="myModal">
  4. Include id="modalText" for the <p> tag inside your modal

In your script section, add the following lines after your existing code (you could utilize jQuery for simplification, but it's not mandatory):

// Obtain <form> element and the modal's <p> element
var formElem = document.getElementById('personalinfo');
var modalTextElem = document.getElementById('modalText');
var modalText;

// Replace the need for onsubmit="ask()"
formElem.addEventListener("submit", ask);

// The e parameter in ask refers to an Event
function ask(e) {
    // Prevent the form from being submitted
    e.preventDefault();

    // Make an AJAX POST request to send data to the server
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'process.php');

    // Implement a callback function for handling the response
    xhr.onload = function() {

        if (xhr.status === 200) { // HTTP status 200 = OK
            var data = JSON.parse(xhr.responseText);
            modalText = 'Thank you ' + data.firstname +
                ', for signing up with us! You can now proceed to the test.';
        } else if (xhr.status !== 200) {
            modalText = 'Request failed. Returned status of ' + xhr.status +
                ' with error: <b>' + xhr.responseText + '</b>';
        }
        modalTextElem.innerHTML = modalText;
        modal.setAttribute("display", "block"); // Show the modal
    };

    xhr.send(new FormData(formElem)); // Send the request
}

Here is an example of server-side processing in PHP (process.php residing in the same directory as your HTML form):

<?php
function validataData() {
    if( strlen($_POST['firstname'] ) < 2 ) {
        return "first name is too short (2+ characters required)";
    }
    if( strlen($_POST['lastname'] ) < 2 ) {
        return "last name is too short (2+ characters required)";
    }
    return "";
}
$validationResult = validataData();

if( !empty($validationResult) ) {
    http_response_code(400); // Return an error response (400 bad request)
    die($validationResult);
}

echo json_encode($_POST); // Return form data as JSON
die();

Do note that this implementation serves as a quick solution and should be customized for real-world scenarios where more extensive server-side validation and processing may be required, such as checking database entries before allowing sign-ups. If you have any doubts, feel free to seek clarification.

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 in AngularJS: Failed to retrieve data using $http.post()

One of my current challenges involves: Transferring text data from HTML form text boxes to the Controller using ng-model and ng-submit directives. Sending this data from the controller to a Service. The Issue at Hand: - I am facing difficulties accessi ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

Cookie parsing functionality in Node JS malfunctioning

Currently, I am working through a tutorial on cookie management in Express JS found at . The goal is to implement cookies in my web application to authenticate requests to an API that I am constructing with Node JS. To set the cookie upon user login, I emp ...

Angular JS Unveiled: Deciphering HTML Entities

I'm looking for a solution to decode HTML entities in text using AngularJS. Here is the string I have: "&quot;12.10 On-Going Submission of &quot;&quot;Made Up&quot;&quot; Samples.&quot;" I need to find a way to decode this u ...

How can I turn off the animation for a q-select (quasar select input)?

I'm just starting out with Quasar and I'm looking to keep the animation/class change of a q-select (Quasar input select) disabled. Essentially, I want the text to remain static like in this image: https://i.stack.imgur.com/d5O5s.png, instead of c ...

Revive the JavaScript library for handling mouse wheel events

Utilizing the wheel-indicator JavaScript library, I am looking to revert the mouse wheel event back to its original state after it was initially set to preventDefault(). Despite attempting to use indicator.setOptions({preventMouse:"false"}) as suggested b ...

Creating dynamic URL routes for a static website using Vue

I am facing a challenge with my static site as I am unable to add rewrites through htaccess. Currently, our site is built using Vue on top of static .html templates such as \example\index.html. When I want to create a subpage within this layout, ...

Confirm that the method has been called by utilizing the AVA testing framework

As I work on creating a unit test for my React component using tools like Ava and Enzyme, I encounter an issue. My goal is to create a simple unit test that checks if a certain method has been called. The test should pass if the method has indeed been call ...

Please ensure that the table is empty before reloading data into it

I am facing an issue while binding data from the database. The data is being bound every 5 seconds, however, it does not clear the previous data and keeps accumulating. Instead of displaying just 3 rows when there are 3 in the database, it adds 3 rows ev ...

Utilizing the Filter Function to Eliminate an Element from an Array

I am a beginner in the world of React and I'm currently working on developing a simple timesheet tool where users can add tasks and save them. My tech stack includes React and Typescript. Currently, my main component has an empty array for tasks and ...

What causes my Excel file to become corrupted when inputting new data?

My intention with this code is to insert "ABC" into cell B3 of an existing Excel document. However, when the file is written, its size decreases significantly and Excel is unable to open it. const excel = require("exceljs"); const template = "./myexcel.xl ...

Error in NextJS: Attempting to access a length property of null

Does anyone have insights into the root cause of this error? warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works TypeError: Cannot read properties of null (reading 'lengt ...

Converting a buffer to a string in Python 3, similar to Node.js 6.0.0

I am currently in the process of translating an old node.js library into Python and I am facing difficulties trying to replicate the behavior of Buffer.toString() in Python. The library is used in a node 6.0.0 environment. While researching, I came acros ...

unable to include Cross-Origin header in ajax request

Whenever I include the HTTP_X_REQUESTED_WITH header in my ajax requests to another server, I encounter an error stating: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.xxxxxxxxxxxx.com/checkurl.php? ...

JavaScript is unresponsive and fails to display

I attempted to incorporate my initial Javascript snippet into a browser to observe its functionality. However, upon adding these lines directly into the body of my HTML code (even though I am aware that there are more efficient methods), no visible changes ...

How can Swipe support help you slide a menu back in?

For implementing swipe support on my landing page carousel, I included jquery.mobile.custom.min.js. However, I am facing a challenge with adding swipe support to "close" the menu. Essentially, swiping left should have the same effect as clicking the butto ...

Use of image tag inside the title attribute

After coming across the question on how to add an image tag inside the title attribute of an anchor tag and finding only one answer claiming it's impossible, I stumbled upon a page where it was actually done: I decided to view the source of the page ...

Dynamically adjusting the width of an HTML element with ng-style using percentage values in AngularJS

I am facing a challenge where I need to display a progress bar in my UI based on a percentage value stored in a JSON response object. Here is an example of the JSON object: { completionPercent: 42 } The desired UI outcome should look like this: ┌ ...

Issues with my transpiled and typed TypeScript npm module: How can I effectively use it in a TypeScript project?

I'm trying to experiment with TypeScript. Recently, I created a simple "hello world" TypeScript module and shared it on npm. It's very basic, just has a default export: export default function hello(target: string = 'World'): void { ...

Guide to building a multi-dimensional array from a flat object

My endpoint is outputting data in a specific format: const result = [ {id: 4, parentId: null, name: 'Fruits & Veggies'}, {id: 12, parentId: 133, name: 'Sanguinello'}, {id: 3, parentId: 4, name: 'Fruits'}, {id: 67, ...