geetarista (owner)

Fork Of

gist: 147052 by jnunemaker jQuery and Rails form errors

Revisions

gist: 147168 Download_button fork
public
Public Clone URL: git://gist.github.com/147168.git
Embed All Files: show embed
errors.js #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
(function($) {
  // errors is an array of errors
  // render :json => {:errors => @item.errors.full_messages}
  function FormErrors(errors) {
    var self = this,
        error_count = errors.length;
 
    this.html = function() {
      var html = '';
      html += '<div class="errorExplanation" id="errorExplanation">';
      html += errorHeading();
      html += errorUl();
      html += '</div>';
      return html;
    }
 
    function errorUl() {
      var lis = $(errors).inject('', function(lis) {
        lis += '<li>' + this + '</li>';
        return lis;
      });
 
      return '<ul>' + lis + '</ul>';
    }
 
    function errorHeading() {
      var error_str = error_count == 1 ? 'error' : 'errors';
      return '<h2>' + error_count + ' ' + error_str +' prevented this form from being saved</h2>';
    }
  }
 
  $.fn.removeErrors = function() {
    return this.each(function() {
      $(this).find('.errorExplanation').remove();
    });
  }
 
  $.fn.showErrors = function(errors) {
    return this.each(function() {
      $(this).removeErrors().prepend(new FormErrors(errors).html());
    });
  }
})(jQuery);
 
example.js #
1
2
3
4
5
6
7
// assumes that errors are output like rails with class of errorExplanation and that the errors are inside the form; to get the error array you can just render :json => @item.errors.full_messages when a thing is invalid
 
// this will remove the errors that exist and add the new errors to the form
$('#new_item').showErrors(["Title can't be blank", "Body is too long"]);
 
// this will remove any errors that exist in a form
$('#new_item').removeErrors()