Jquery Validation errorPlacement / submitHandler

感情迁移 提交于 2019-12-25 08:05:21

问题


How do I write my js so that the responses from the jquery validation plugin are placed inside the form field boxes?

The html form looks like:

<form class="cmxform" id="commentForm" method="POST" action="">
<p>
 <label for="cname">Name</label>
 <input id="cname" type="text" name="name" size="60" class="required" minlength="2" />
</p>
<p>
 <label for="cemail">E-Mail</label>
 <input id="cemail" type="text" name="email" size="60"  class="required email" />
</p>
<p>
 <label for="curl">URL</label>
 <input id="curl" type="text" name="url" size="60"  class="url" value="" />
</p>
<p>
 <label for="ccomment">Your comment</label>
 <textarea id="ccomment" type="text" name="comment" cols="72" rows="8"  class="required"></textarea>
</p>
<p>
 <div id="button2"><input class="submit" id="submit_btn" type="submit" value="Send Email"/></div>
</p>
</form>

The js currently looks like this:

<script>
$(document).ready(function() {
    $('#commentForm').validate({
        submitHandler: function(form) {
            $.ajax({
                type: 'POST',
                url: 'process.php',
                data: $(this).serialize(),
                success: function(returnedData) {
                    $('#commentForm').append(returnedData);
                }
            });         
            return false;
        }
    });
});
</script>

Whats the proper js to put the errorPlacement inside the form fields' input value? So that if someone didn't include their email the response "this field is required" will appear inside the input value for email. Currently, it is returned after the input. Thank you.


回答1:


Validation offers the option errorPlacement which is a function for exactly this purpose.

I wrote this up quickly for you using jQuery UI's position utility (so you'd have to include jQuery UI to make my version work):

  //in your $.validate options, add this
  errorPlacement: function(error, element) {
      error.insertAfter( element).position({
          my:'right top',
          at:'right top',
          of:element          
      });
   }  

Note I also defined this CSS:

label.error { color: red; position:absolute; }​

See it in action here: http://jsfiddle.net/ryleyb/Z64Tv/



来源:https://stackoverflow.com/questions/9559506/jquery-validation-errorplacement-submithandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!