简体   繁体   English

简单的表单跳过验证/发送,直接进入ajax消息

[英]Simple form skips validation/sending and goings straight to ajax message

I have been following this tutorial to validate a form on a HTML5 template I am working on modifying. 我一直在遵循本教程来验证我正在修改的HTML5模板上的表单。 Here is the link: http://englishpearls.net/dev/contact.html 这是链接: http : //englishpearls.net/dev/contact.html

As you see, the form goes straight to the ajax message and skips everything else. 如您所见,表单直接进入ajax消息,并跳过其他所有内容。 What am I doing wrong? 我究竟做错了什么?

HTML HTML

<div id="contact_form">
    <form method="post" action="contact-post.html" >
    <div class="to">
        <input id="name" for="name" type="text" class="text" value="Name" name="userName" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">
        <label class="error" for="name" id="name_error">This field is required.</label>
        <input id="email" type="text" class="text" value="Email" name="userEmail" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}" style="margin-left: 10px">
        <label for="email" class="error" for="email" id="email_error">This field is required.</label>
    </div>
    <div class="to">
        <input id="phone" for="phone" type="text" class="text" value="Phone" name="userPhone" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Phone';}">
        <label class="error" for="phone" id="phone_error">This field is required.</label>
        <input id="subject" type="text" class="text" value="Subject" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Subject';}" style="margin-left: 10px">
        <label class="error" for="subject" id="subject_error">This field is required.</label>
    </div>
    <div class="text">
        <textarea id="message" value="Message:" name="userMsg" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Message';}">Message:</textarea>
        <label class="error" for="message" id="message_error">This field is required.</label>
    </div>
    <div>
        <input class="button" type="submit" value="Submit" name="submit" />
    </div> 
</div>

Jquery EDIT: Updated Script jQuery编辑:更新脚本

    <script type="text/javascript">

            $(function() {
  $('.error').hide();
  $(".button").click(function() {
    // validate and process form here

    $('.error').hide();
    var name = $("input#name").val();
      if (name == "") {
      $("label#name_error").show();
      $("input#name").focus();
      return false;
    }
      var email = $("input#email").val();
      if (email == "") {
      $("label#email_error").show();
      $("input#email").focus();
      return false;
    }
      var phone = $("input#phone").val();
      if (phone == "") {
      $("label#phone_error").show();
      $("input#phone").focus();
      return false;
    }
     var subject = $("input#subject").val();
      if (subject == "") {
      $("label#subject_error").show();
      $("input#subject").focus();
      return false;
    }
     var message = $("input#message").val();
      if (message == "") {
      $("label#message_error").show();
      $("input#message").focus();
      return false;
    }

var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&subject=' + subject + '&message=' + message;
//alert (dataString);return false;
$.ajax({
  type: "POST",
  url: "contact-post.html",
  data: dataString,
  success: function() {
    $('#contact_form').html("<div id='message'></div>");
    $('#message').html("<h2>Contact Form Submitted!</h2>")
    .append("<p>We will be in touch soon.</p>")
    .hide()
    .fadeIn(1500, function() {
      $('#message').append("<img id='checkmark' src='web/images/check.jpg' />");
    }); 
  }
});
return false; 

  });

});


</script>

Without the validation script, the email sends fine. 没有验证脚本,电子邮件可以正常发送。 Thanks! 谢谢!

The way your script is setup right now, the AJAX call will fire immediately, regardless of any input. 现在就设置脚本的方式,无论有任何输入,AJAX调用都会立即触发。 It needs to be inside of this: 它必须在其中:

$(".button").click(function () { } $(“。button”)。click(function(){}

function, which should have an if statement that will only allow the AJAX to fire if the validation of the form is successful. 函数,该函数应具有if语句,该语句仅在表单验证成功后才允许AJAX触发。

Updated: 更新:

<div id="contact_form">
    <form id="contact-post" method="post" action="contact-post.html" >
    <div class="to">
        <input id="name" for="name" type="text" class="text" placeholder="Name" name="userName" >
        <label class="error" for="name" id="name_error">This field is required.</label>
        <input id="email" type="text" class="text" placeholder="Email" name="userEmail" style="margin-left: 10px">
        <label for="email" class="error" for="email" id="email_error">This field is required.</label>
    </div>
    <div class="to">
        <input id="phone" for="phone" type="text" class="text" placeholder="Phone" name="userPhone" >
        <label class="error" for="phone" id="phone_error">This field is required.</label>
        <input id="subject" type="text" class="text" placeholder="Subject"style="margin-left: 10px">
        <label class="error" for="subject" id="subject_error">This field is required.</label>
    </div>
    <div class="text">
        <textarea id="message" placeholder="Message:" name="userMsg">Message:</textarea>
        <label class="error" for="message" id="message_error">This field is required.</label>
    </div>
    <div>
        <input class="button" type="submit" value="Submit" name="submit" />
    </div> 

JS: JS:

<script type = "text/javascript">

    $(function () {
        $('.error').hide();
        $("#contact-post").submit(function (event) {
            alert("submitted");
            event.preventDefault();
           // validate and process form here
            $('.error').hide();
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var subject = $("input#subject").val();
            var message = $("#message").val();


            if (name == "") {
                $("label#name_error").show();
                $("input#name").focus();
            } else if (email == "") {
               $("label#email_error").show();
               $("input#email").focus();
            } else if (phone == "") {
                $("label#phone_error").show();
                $("input#phone").focus();
            } else if (subject == "") {
                $("label#subject_error").show();
                $("input#subject").focus();
            } else if (message == "") {
                $("label#message_error").show();
                $("input#message").focus();
            } else {
                var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone + '&subject=' + subject + '&message=' + message;
                $.ajax({
                    type: "POST",
                    url: "app/contact.php",
                    data: dataString,
                    success: function () {
                        $('#contact_form').html("<div id='message'></div>");
                        $('#message').html("<h2>Contact Form Submitted!</h2>")
                        .append("<p>We will be in touch soon.</p>")
                        .hide()
                        .fadeIn(1500, function () {
                            $('#message').append("<img id='checkmark' src='web/images/check.jpg' />");
                        });
                    }
                });  
            }
       });
    });
< /script>

That will work. 那可行。 Also I changed all of the value attributes in your HTML to placeholder attributes so they function as expected and don't get in the way of the validation. 另外,我将HTML中的所有value属性更改为占位符属性,以便它们按预期运行,不会妨碍验证。

Alternatively, since you're already using jQuery, you could check out jQuery Validate , a jQuery plugin that would make this much simpler 另外,由于您已经在使用jQuery,因此可以查看jQuery Validate ,这是一个jQuery插件,可以简化此工作

UPDATE: 更新:

I removed all of the onfocus/onblur attributes from your HTML and it works now. 我从HTML中删除了所有onfocus / onblur属性,现在可以使用了。 The JS in the onblur tags was filling the form with values, so it was able to pass validation. onblur标记中的JS用值填充了表单,因此它能够通过验证。 Look at this JSFIDDLE for a working verison 查看此JSFIDDLE以获取有效版本

UPDATE 2: 更新2:

The var message = $("input#message").val() should be var message = $("#message").val() . var message = $("input#message").val()应该是var message = $("#message").val() The first one is looking for an input with the id of "message", where as you have a textarea with that id. 第一个是寻找一个ID为“ message”的输入 ,因为您有一个具有该ID的文本区域 Changing this line will correct the blank message you're getting. 更改此行将纠正您收到的空白消息。 (see the updated JS above) (请参阅上面的更新的JS)

Regarding this question, 关于这个问题

I have noticed that in the first link I have the $(".button").submit(function (event) whereas in your config, in the same spot you have $("#contact-post").submit(function (event) 我注意到,在第一个链接中,我有$(“。button”)。submit(function(event),而在您的配置中,同一位置有$(“#contact-post”)。submit(function(事件)

I have the validation being performed when a form with the id of "contact-post" gets submitted, instead of when the button gets submitted (which isn't possible). 我将在提交具有“ contact-post” ID的表单时而不是在提交按钮时进行验证(这是不可能的)。 The reason the page with this JS/form is submitting is that the JS to validate never gets triggered. 带有此JS /表单的页面提交的原因是,从未触发过要验证的JS。

It's possible (although unlikely) to submit the form without clicking that button, so we don't want the validation to be skipped on the off-chance that happens. 可以(尽管不太可能)不单击该按钮即可提交表单,因此我们不希望在发生这种情况时跳过验证。

You could try adding "return true;" 您可以尝试添加“ return true;”。 to the .click 到.click

$(".button").click(function () { 
   //...
   //validation code
   //...
   //return true if passes validation
  return true; 
}

Have you thought about combining things like this: 您是否考虑过将以下内容组合在一起:

$('yourForm').on('submit', function(event){
    if ( formIsvalid() ) {
      $.ajax({
          ...
        });
    } else {
        // Do something else maybe?
    }
    event.preventDefault();
});

// Form validation.
function formIsvalid() {
  ... form validation here...
  return true;
}

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

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