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

Label the timeline map generated with the leaftime plug-in for leaflet in R with the appropriate tags

Here is a code snippet extracted from the R leaftime package documentation examples. It generates a map with a timeline that displays points as they appear over time. I am interested in adding labels to these points to show their unique id numbers. Upon ...

Determining the data type of a textbox value in JavaScript: String or Number?

I am encountering an issue with the code below: <input type="text" value="123" id="txtbox"> <script> var myVar = document.getElementById('txtbox').value; if (myVar.substring) { alert('string'); } else{ alert('number&a ...

Loading pages asynchronously using Ajax with added interactivity through custom JavaScript scripts

Using jQuery Masonry in conjunction with another JavaScript for voting, here is the code: <div id="contain"> <?php $result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20"); while($row = mysqli_fetch_array($result ...

How to resolve the error of "Objects are not valid as a React child" in NextJs when encountering an object with keys {children}

I am currently working on a nextjs application and I have encountered an issue with the getStaticPaths function. Within the pages folder, there is a file named [slug].tsx which contains the following code: import { Image } from "react-datocms"; i ...

A tutorial on how to create the appearance of disabled buttons that look the same as enabled buttons through the use

My button includes a text field that is constantly disabled. I would like for the text field to appear as bright as it does when the button is enabled. After disabling the button, they both appear dimmer compared to others and the text field follows suit ...

Save log discrepancies to a document

Upon completing my website for graduation, there is still one important feature I want to add. I would like to implement a script that sends the name of the website where it is installed, as well as any error messages, to my website. For instance: The fol ...

Determine whether the response from a jQuery AJAX call is in JSON format or binary. If it is found to be binary, proceed

I am currently using ajax to retrieve and download an xlsx file from a PHP script. The script has two possible types of responses: JSON format if there are any warnings preventing the download (such as incorrect parameters), or the xlsx binary stream if ev ...

Having trouble making JSON work alongside Ajax and jQuery?

In my JavaScript, I have the following code snippet... $.ajax({ type: 'POST', url: 'http://www.example.com/ajax', data: {email: val}, success: function(response) { alert(response); } }); The PHP fil ...

The functionality of a button within a web component is restricted to only trigger the click event once after it has been

I am facing an issue with my class that includes three buttons for navigating the app. The event listeners I add to these buttons in the connectedCallback method only work once. When I click one of the buttons, like the next button, it changes the attribut ...

Is it common to have numerous operations in a single controller in AngularJS?

<!DOCTYPE html> <html ng-app="myApp" > <head> <title>myApp.html</title> </head> <body ng-controller="myCtrl as vm"> <br><br> <div> <p> I ...

Include an extra hyperlink in the adaptive menu bar

I have successfully created a responsive Navigation bar. Now, I would like to add an "Account" link on the right side of the navigation. My initial thought was to insert a div into a ul element, but I realize that this may not be W3C compliant. <div c ...

Struggling to populate React Components with JS objects only to encounter the error message "Functions cannot be used as React children"?

I'm still getting the hang of React, so please bear with me if this is a simple issue. My goal is to utilize a JavaScript Object: const gameCardData = { "university": { "elemental-wars": { "imgAlt": "Elemental Wars Start Screen", " ...

I am encountering an issue with a JS addition operator while working with node.js and fs library

I'm trying to modify my code so that when it adds 1 to certain numbers, the result is always double the original number. For example, adding 1 to 1 should give me 11, not 2. fs.readFile(`${dir}/warns/${mentioned.id}.txt`, 'utf8', ...

What could be causing the issue of images not loading in Chrome while they are loading perfectly in Mozilla when using CSS3?

Recently, I dove into a project utilizing react with webpack, and everything was smooth sailing until I encountered the CSS hurdle. Despite successfully configuring webpack, trouble brewed when it came to styling. Specifically, setting the background image ...

Vanilla JS Rock, Paper, Scissors Game - Fails to reset classes upon restarting

Many questions have been raised about this particular topic, but a solution for vanilla js seems elusive. Let's delve into a new challenge: Rock paper scissors with vanilla js. The game functions properly on its own, but the issue arises when attemp ...

Display different text based on the property value

I need to display different text based on the value of a property, showing "offline" if camera.key is null and "online" otherwise. Here's the template I'm using: <h3>Camera sensors</h3> <table> <th>Name</th> ...

Basic AngularJS framework with minimal external dependencies

I have been searching for an AngularJS skeleton to set up my project, but it seems like all the skeletons I find online require the installation of numerous dependencies through npm and/or bower. Due to security concerns at the firm where I am working on ...

Linking model attribute to checkbox in AngularJs

Currently, I am working on assigning tags during post creation. For this purpose, I have set up a Post model with the following structure: var mongoose = require('mongoose'); var PostsSchema = { title: String, content: String, poste ...

working with html data in a bootstrap modal using javascript

Utilizing an id, I pass data to a bootstrap modal and link that id with stored data. $("#fruit").html($(this).data("fruit")); In addition, I am appending data to the bootstrap modal $('#mymodal').find('.modal-body').append('< ...

How come my countdown application functions properly when accessed through the browser via the HTML page, but encounters issues when utilized with an HTTP server?

I have encountered an issue where the app functions correctly when I open the HTML file in my browser, but fails to load the CSS and JavaScript when accessing it through localhost:3000. HTML: <html> <head> <link href="./main.css" rel="st ...