client_side_validations (3.1.0) not working when new form is added to the DOM

后端 未结 2 1916
情深已故
情深已故 2021-01-14 03:07

I\'m using Rails 3.1.0rc4 and client_side_validations 3.1.0. Everything works perfectly so long as the form is rendered in the main request. However, if the form itself is

相关标签:
2条回答
  • 2021-01-14 03:56

    Found the answer in the javascript source code for this gem:

    // Main hook
    // If new forms are dynamically introduced into the DOM the .validate() method
    // must be invoked on that form
    $(function() { $('form[data-validate]').validate(); })
    

    So, in my particular case, I needed to do:

    #jobs/new.js.erb
    $('#form-job-new').append("<%= escape_javascript render(:file => 'jobs/new.html.erb') %>");
    $('form[data-validate]').validate();
    
    0 讨论(0)
  • 2021-01-14 04:01

    Depending on how much you use ujs (i do a lot) it might make more sense to do something like this instead of calling the validate method in every ujs file.

    $('body').bind("ajax:success", function() {
       if($('form[data-validate]').length){
          $('form[data-validate]').validate();
       }
    });
    

    or coffeescript

    $("body").bind "ajax:success", ->
      $("form[data-validate]").validate()  if $("form[data-validate]").length
    
    0 讨论(0)
提交回复
热议问题