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

非 Y 不嫁゛ 提交于 2019-12-01 08:20:29

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();

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