首页 > 解决方案 > 提交表单时未显示警报消息

问题描述

我刚开始学习 HTML/JavaScript。我有一个表单,提交时它应该向用户显示输入数据,我尝试了警报和 .html() 方法,但似乎都没有显示信息。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />

    <script src="scripts/jquery-3.2.1.js"></script>
    
    <script>
        function displayInfo() {
            let product = ($('#productName').val());
            let quantity = parseInt($('#qty').val());

            if ($('#delivery:checked').val() == 'y'){
                let delivery = "Delivery required";
            }
            else{
                let delivery = "Delivery not required";
            }
            var info = "Product name: " + product + "<br>" + "Quantity: " + quantity + "<br>" + "Delivery?:" + delivery;
            $("#info").html(info);
            
        }
    </script>

</head>
<body>
    <h1>Example page</h1>
    
    <form onsubmit="displayInfo(); return false;">
        <p>Enter the name of the product you want to buy: <input type="text" id="productName"/></p>
        <p>Enter the quantity you want to buy: <input type="text" id="qty" /></p>
        <p>Do you require delivery? <input type="checkbox" id="delivery" value="y" /></p>
        <p><input type="submit" value="Place order" /></p>
    </form>

    <div id ="info"></div>
</body>
</html>

并且

            alert("Product name: " + product + "<br>" + "Quantity: " + quantity + "<br>" + "Delivery?:" + delivery);

标签: javascripthtmljquery

解决方案


您可能jQuery错误地设置了库的路径。此外,您需要delivery在使用它的同一级别上声明。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>    
    <script>
        function displayInfo() {
            const product = ($('#productName').val());
            const quantity = parseInt($('#qty').val());
            let delivery = "Delivery not required";
            if ($('#delivery')[0].checked){
                delivery = "Delivery required";
            }
            const info = "Product name: " + product + "<br>" + "Quantity: " + quantity + "<br>" + "Delivery?: " + delivery;
            $("#info").html(info);
            
        }
    </script>

</head>
<body>
    <h1>Example page</h1>
    
    <form onsubmit="displayInfo(); return false;">
        <p>Enter the name of the product you want to buy: <input type="text" id="productName"/></p>
        <p>Enter the quantity you want to buy: <input type="text" id="qty" /></p>
        <p>Do you require delivery? <input type="checkbox" id="delivery" value="y" /></p>
        <p><input type="submit" value="Place order" /></p>
    </form>

    <div id ="info"></div>
</body>
</html>


推荐阅读