How can I dynamically add and remove form fields to be validated by Parsley.js?

前端 未结 3 704
我在风中等你
我在风中等你 2020-12-15 06:32

I have a form (\'#registrations\') that I am validating with Parsley.js and so far it is working fine. However, I am trying to dynamically remove form fields and add new one

3条回答
  •  轮回少年
    2020-12-15 07:07

    Once the new field has been added to Parsley, you need to add the required constraint to that field.

    //add corresponding models select to parsely
    $('#registrations').parsley('addItem', '#'+manufacturer+'-models');
    
    //add required constraint 
    $('#'+manufacturer+'-models').parsley('addConstraint', {
        required: true 
    });
    

    Update (April 10, 2014)

    The above works for Parsley.js 1.x but not for Parsley 2.x.

    Parsley 2.x doesn't use addItem, removeItem, addConstraint, or removeConstraint.

    Instead, Parsley 2.x will automatically detect changes in your form based on the data attributes each input has. In the above example, if you wanted to add a new item to Parsley, you would do the following:

    //destroy parsley
    $('form').parsley().destroy();
    
    //set required attribute on input to true
    $('input').attr('data-parsley-required', 'true');
    
    //reinitialize parsley
    $('form').parsley();
    

    Likewise, if you wanted to remove an item from Parsley, you would do:

    //destroy parsley
    $('form').parsley().destroy();
    
    //set required attribute on input to false
    $('input').attr('data-parsley-required', 'false');
    
    //reinitialize parsley
    $('form').parsley();
    

提交回复
热议问题