确认用户输入并显示输出然后提交表单

时间:2015-07-09 19:39:38

标签: javascript php jquery forms

我想用一个用户表单输入,要求用户确认并向他们展示他们的选择,然后只有在他们确认之后才将表单提交给服务器。我不确定该如何解决这个问题? 谢谢, 到目前为止,这是我的代码:

<?php

$q = intval($_GET['q']);
$e = strval($_GET['e']);

echo "Data received = >" . $q . "< and >" . $e . "<";  // DATA RETURNED (FOR TESTING ONLY).
/*
$servername = "localhost";
$username = "*****";
$password = "*****";
$dbname = "*****";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql = "UPDATE Games SET entries=$e WHERE PINs=$q";
$result = $conn->query($sql) or die($conn->error);

$conn->close();
*/
?>

form.php的

<form id="myform" action="form.php" method="post">
    <?php
        echo "<ul>";

        foreach($dir as $item) {
            $items = basename($item);
            $str = str_replace("+", " ", $items);
            if (strpos($str, 'test') === false) {
                if (strlen($str) == 3) {
                    $strs = ucwords(strtoupper($str));
                    echo "<li><label><input type = 'checkbox' class='check-class' name='chk[]' id='strs[]' value=$items>$strs</label></li>";
                } else {
                    $strs = ucwords($str);
                    echo "<li><label><input type='checkbox' class='check-class' name='chk[]' id='strs[]' value=$items>$strs</label></li>";
                }
            }
        }

        echo "</ul>";
    ?>

    <div style="text-align:center">
        <input type="submit" style="font-face:'Comic Sams MS';font-size:larger;color:red;background-color:#FAF0E6;border:3pt ridge lightgrey;" value="Click to Submit">
    </div>
</form>

<div id="success"></div>

<script type="text/javascript">
    $(function() {
        $('#myform').submit(function() {
            $.ajax({
                data: $(this).serialize(),
                type: $(this).attr('method'),
                url: $(this).attr('action'),
                success: function(data) {
                    $('#success').html(data);
                }
            });
            return false;
        });
    });
</script>

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用window.confirm

$('#myform').submit(function() {
    var selectedItemsText = '';
    $(this).find('input[type="checkbox"]:checked').each(function(){
        selectedItemsText  += $(this).val() +'\r';
    });

    if(confirm('Are you sure? You've selected:\r'+selectedItemsText)){
        $.ajax({
            data: $(this).serialize(),
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            success: function(data) {
                $('#success').html(data);
            }
        });
    }
    return false;
});

Check out this Fiddle.我出于显而易见的原因省略了AJAX。

有更好的方法可以做到这一点。例如,您可以使用jQuery UI Dialog(或等效物)。但是对于快速,肮脏,简单的解决方案 - 只需使用confirm