通过javascript进行表单验证-出现错误警报,但保存了数据

问题描述 投票:1回答:1

这里我正在比较位置名称,无论它是否已经输入,在我的代码中,当我单击“提交”按钮但还提交数据时,我都会收到警报。 onchange函数无法按预期工作,有人可以帮助我如何在收到警报时停止不提交的数据?在提交时间验证时,为什么要这样做,原因是在我们的测试服务器中,单击按钮后会出现一些延迟,因此也仅在警报后提交数据。你对此有什么想法吗?在此先感谢

 <form class="form-inline" id="desgForm" accept-charset="UTF-8" method="post" action="../locationSubmit.htm" enctype="multipart/form-data">

<input type="text" id="locationName" autocomplete="off"  name="locationName"  class="form-control validate[required]" onchange="desgCheck();" onkeyup="firstToUpperCase1();" value="">

<button type="submit" class="btn btn-primary" >Save</button>

</form>

Javascript:

<script>
function desgCheck()
            {
                var locationName = document.getElementById('locationName').value;


                $.ajax({
                    type: "POST",
                    url: "../designation/locationName.htm",
                    data: {
                        locationName: locationName
                    },
                    dataType: "text",
                    success: function (data)
                    {
                        if ($.trim(data) !== 'Data  available')
                        {
                            alert("This Location already exist!!");
                            document.getElementById("locationName").value = "";


                            return false;
                        }

                    },
                    error: function (error) {
                        document.getElementById("locationName").value = "";
                    }
                });

            }


            function firstToUpperCase1() {
                var str = document.getElementById("locationName").value;
                var a = str.toUpperCase();
                $("#locationName").val(a);
            }

            jQuery("#desgForm").validationEngine();
</script>
javascript forms validation
1个回答
0
投票

如果验证在ajax成功回调中失败,您可以禁用提交按钮,例如:

success: function(data) {
  if ($.trim(data) !== 'Data  available') {
    alert("This Location already exist!!");
    document.getElementById("locationName").value = "";

    $(':input[type="submit"]').prop('disabled', true);
  } else {
    $(':input[type="submit"]').prop('disabled', false);
  }
},

然后,用户将完全无法单击提交按钮,最终将无法提交表单。

我在这里使用通用的提交按钮选择器,例如$(':input[type="submit"]'),假设您在当前页面中只有一个提交按钮。如果页面上有多个提交按钮,请为该按钮分配一个ID并使用它来代替

$('#mySubmitButtonId').prop('disabled', true);
© www.soinside.com 2019 - 2024. All rights reserved.