驗證多個class相同的input框不爲空

要求,頁面有多個class相同的input輸入框,在提交數據的時候,進行驗證,驗證input框不能爲空,如果哪個爲空,則彈出提示:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>驗證多個class相同的input框不爲空</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
        <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
        <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    </head>
    <body>
        司乘卡號: <input class="personDeviceId" type="text" /><br />
        司乘卡號: <input class="personDeviceId" type="text" /><br />
        司乘卡號: <input class="personDeviceId" type="text" /><br />
        <button type="button" class="btn blue" id="addBtn">保存</button>
    </body>
    <script type="text/javascript">
        $("#addBtn").on("click", function() {
            //驗證車乘
            var personDeviceId = ($(".personDeviceId").length);
            for (var i = 0; i < personDeviceId; i++) {
                if ($(".personDeviceId").eq(i).val().length == 0) {
                    alert("第" + (i + 1) + "個司乘卡號爲空");
                    return;
                };
            };
        })
    </script>
</html>

效果如下圖所示


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章