简体   繁体   English

表单提交(ajax)不适用于提交(仅适用于单击),但是在第二个选项中不验证字段

[英]Form submission (ajax) does not work with submit (only with click) but in the second option does not validate fields

I have a clasic form submition with ajax but it only works with $("button").click(function()and so it does not validate fileds properly. 我使用ajax进行经典表单提交,但仅适用于$(“ button”)。click(function(),因此无法正确验证文件。

<script type="text/javascript">
$(document).ready(function(){
    $( ".response" ).hide();
});
$(document).ready(function(){
   $(".gumb").click(function(){
   event.preventDefault();

        var formData = $('#my_form').serialize();
         var pogoji = $("#pogoji").val();
        var email = $("#email").val();
        var dataString = 'pogoji='+ pogoji + '&email=' + email;

        $.ajax({
            url:"action_page.php", 
            type: "POST",
            data: dataString, 
            success:function(result){

               $( ".response" ).show();
               $( "#obrazec" ).hide();
            $( ".prijavatext" ).hide();
            }
        });
    });
});
</script>

<html>
      <form name="Form" id="obrazec">

  <input id="email" type="email" name="email" placeholder="E-poštni naslov" required />
            <br>
      <input id="pogoji" type="checkbox" name="pogoji" value="Pogoji" required /> <label style="">Strinjam se s pogoji</label>
        <br>
 <button class="gumb" form="obrazec" type="submit" onclick>Potrdi</button>


</form> 
</html>

I know it should work with submit: $("button").submit(function(); why it does not work? Or if click is ok, how to make form validate fields? 我知道它应该与submit一起使用:$(“ button”)。submit(function();为什么不起作用?或者如果单击确定,如何使表单验证字段?

 $(document).ready(function(){ $( ".response" ).hide(); }); $(document).ready(function(){ $("#obrazec").submit(function(event){ event.preventDefault(); alert('submitted with html validation working'); var formData = $('#my_form').serialize(); var pogoji = $("#pogoji").val(); var email = $("#email").val(); var dataString = 'pogoji='+ pogoji + '&email=' + email; /*$.ajax({ url:"action_page.php", type: "POST", data: dataString, success:function(result){ $( ".response" ).show(); $( "#obrazec" ).hide(); $( ".prijavatext" ).hide(); } });*/ }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <form name="Form" id="obrazec"> <input id="email" type="email" name="email" placeholder="E-poštni naslov" required /> <br> <input id="pogoji" type="checkbox" name="pogoji" value="Pogoji" required /> <label style="">Strinjam se s pogoji</label> <br> <input class="gumb" form="obrazec" type="submit" value="Potrdi"> </form> </html> 

Use Jquery submit method and pass the event in submit function to prevent the form submit event . 使用Jquery提交方法并在提交函数中传递事件以防止form submit event

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

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