Search code examples
javascriptparsley.js

Getting two errors using Parsley.js to add validators to fields that are dynamically cloned


I have a form which I am using Parsley.js to validate. Everything works like a charm. Except, there is a part of the form where users are allowed to add new fields:

addFieldsToContainer = function($fields, $container) {
    $fields.clone(true).removeClass('empty-form').appendTo($container);

    if (typeof(Parsley) !== 'undefined'){
        $('form.form-horizontal').parsley().destroy();
        addValidatorsListeners();
    }
};

My validations are a little complicated, because there are sections, and in each section, the inputs must all add up to a total number, which is the value of another input. I've got the inputs triggered to blur, and if any of the inputs are entered and the total for the section is wrong, all the inputs for the section are given the parsley-error class, and vice versa. Now, on the new input that is being added to the DOM, the parsley ui is not working on it, i.e. the parsley-success/error classes are not being added to it. But the rest of the section still works fine, and even includes whatever number is in the input in the total calculation. I'm also seeing these two errors in the dev console:

Uncaught TypeError: Cannot set property 'validatedOnce' of undefined parsley.min.js:8 
Uncaught TypeError: Cannot read property '$errorsWrapper' of undefined

My code here.

How can I correctly bind these new inputs to the parsley validator?

Edit: So I just realized that the when the user clicks the add input button, all of the inputs that have parsley:success/error classes have them all removed (because of model_form.parsley().destroy() I assume?) except for the new input that has been added. This input class never changes with the rest of the section, as I've pointed out. Also, the total enrollment input doesn't change, I'm guessing because of the { excluded: '[data-parsley-sum-total="all"]' } line. So it looks like the input that is being cloned from the page isn't having it's binding destroyed or it's validators correctly added, so some sort of event handling problem?

Maybe related?


Solution

  • If you clone Parsley's elements with their data, yeah, Parsley will be confused as hell.

    I'd simply recommend not doing that. More precisely, clone without the data and events, or else clone before binding with parlsey.

    If you really have to go this way, you might be able to get away with cloning afterwards if you $yourClone.removeData('Parsley'). I haven't tested it and can't guarantee that even if it works now it would in the future.