简体   繁体   English

如何满足所有要求后才出现模态框?

[英]How to make modal box appear only after all requirements have been met?

So I have a form, which asks for the user's personal information. 因此,我有一个表格,要求用户提供个人信息。 At the end of the form I have set a modal to pop up, which says "Thank you for signing up with us etc.". 在表格末尾,我设置了一个弹出窗口,上面显示“谢谢您与我们注册等”。 However, even if you leave all the fields blank and you click on the button at the end of the form, the modal still pop up saying "Thank you for signing up with us...". 但是,即使您将所有字段都保留为空白,然后单击表单末尾的按钮,该模式仍会弹出,提示“谢谢您与我们签名...”。

How can I set the modal to appear only after all the fields are completed? 如何设置模式,使其仅在所有字段完成后才显示?

Note: I need the personal information to remain on the page after I click the button at the end of the form. 注意:单击表单末尾的按钮后,我需要将个人信息保留在页面上。 I changed the type from submit to button, but as soon as I fill in the last question and i click on the button, all the input disappears. 我将类型从“提交”更改为“按钮”,但是当我填写了最后一个问题并单击按钮时,所有输入都会消失。

Any help would be much appreciated ! 任何帮助将非常感激 !

Here's 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>

The reason why your form is cleared is that your form is submitted to the server, and hence the page reloaded with an empty form. 清除表单的原因是您的表单已提交到服务器,因此页面重新加载了空白表单。

In my opinion, there are two ways in which you could handle this: 我认为,可以通过两种方式处理此问题:

  1. Classic form submission 经典表格提交
  2. AJAX form submission AJAX表单提交

In the first case you would send your form, process it on the server, and then redirect to a page containing a welcome message (the content of your modal). 在第一种情况下,您将发送表单,在服务器上进行处理,然后重定向到包含欢迎消息(模态内容)的页面。 But in this case your form would be cleared on submission. 但是在这种情况下,您的表格将在提交后清除。

In the second case , you want to do several things in the right order: 在第二种情况下 ,您想要以正确的顺序执行几件事:

  • Send the form data to the server by an AJAX request 通过AJAX请求将表单数据发送到服务器
  • Handle success and error cases 处理成功和错误案例
  • Show your modal, containing a message according to status (success or error) 显示您的模式,根据状态(成功或错误)包含一条消息

As for the code, in your HTML: 至于代码,在您的HTML中:

  1. Remove onsubmit="ask()" from your <form> tag 从您的<form>标记中删除onsubmit="ask()"
  2. Add a type="submit" attribute to your submit button 向您的提交按钮添加type="submit"属性
  3. Add style="display:none" to your <div id="myModal"> . style="display:none"添加到您的<div id="myModal">
  4. Add a id="modalText" attribute to the <p> tag inside your modal 在模态内的<p>标记中添加一个id="modalText"属性

In your script, add the following after your code (you could use jQuery to make it simpler, however this is not mandatory at all, see this ): 在脚本中,在代码后添加以下内容(您可以使用jQuery使其更简单,但这不是强制性的,请参见this ):

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

// This replaces onsubmit="ask()"
formElem.addEventListener("submit", ask);

// The e argument to ask is an Event
function ask(e) {
    // This will prevent the form from being submitted
    // (litterally "prevent default event" from taking place)
    e.preventDefault();

    // Send data to the server via an AJAX POST request
    var xhr = new XMLHttpRequest();
    // process.php would be a server-side script (see below)
    xhr.open('POST', 'process.php');

    // This is what is called a callback:
    // code that will be executed when your request returns
    xhr.onload = function() {

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

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

Then an example of server-side processing in PHP ( process.php located in the same folder as your HTML form): 然后是PHP中服务器端处理的示例( process.php与HTML表单位于同一文件夹中):

<?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();

// On error send an error response (400 bad request with the type of error)
if( !empty($validationResult) ) {
    http_response_code(400);
    die($validationResult);
}

// Otherwise send back form data (by default with error code 200)
echo json_encode($_POST);
die();

Keep in mind that this code is quick'n'dirty stuff, just to address your question. 请记住,此代码是快速的东西,只是为了解决您的问题。

In real-life code,you would ask an email and password in your form, then you would need much more server-side stuff: you would check that the email doesn't already exist in your database, etc. 在实际的代码中,您会要求您以表格的形式发送电子邮件和密码,然后您需要更多的服务器端内容:您将检查电子邮件是否已存在于数据库中,等等。

Feel free to ask if anything isn't clear. 随意询问是否有不清楚的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM