Dougui
Dougui

Reputation: 7232

Dynamic forms with BootstrapValidator

In an application using BootstrapValidator, I have this form :

<form method="post" action="save.php" role="form" id="form" class="form-horizontal">

  <div class="children-list col-sm-12">
    <div class="child col-sm-12">
      <div class="col-sm-12">
        <div class="form-group">
          <label class="col-sm-4 control-label" for="guest">Option 1</label>
          <div class="col-sm-4">
            <div class="radio">
              <label>
                <input type="radio" data-bv-notempty="true" data-bv-notempty-message="test" name="guest[1][member_ski]" value="0"> Yes
              </label>
            </div>
            <div class="radio">
              <label>
                <input type="radio" data-bv-notempty="true" data-bv-notempty-message="test" name="guest[1][member_ski]" value="1"> No
              </label>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="button" href="#" class="btn btn-sm btn-default add-child">Add a child</button>
    </div>
  </div>

  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <input type="submit" class="btn btn-sm btn-default" value="Send"/>
    </div>
  </div>
</form>

And this Javascript :

$(document).ready(function() {
    $('form').bootstrapValidator().on('click', '.add-child', function() {
        list = $('.children-list')[0];
        first = $(list).find('.child:first');
        clone = $(first).clone();
        $.each(clone.find('input'), function(_, input) {
            $(input).attr('name', 'guest[2][member_ski]');
            $(input).attr('data-bv-field', 'guest[2][member_ski]');
        });
        $(list).append(clone);
        $('form').bootstrapValidator('addField', clone);
    });


    $('.btn.remove-child').hide();
});

When I click on the button to add a new child, and I submit the form, the first validation is working but not the second. Is there a wat to make it working both?

Upvotes: 0

Views: 767

Answers (1)

minnow73
minnow73

Reputation: 26

I ran into the same problem and noticed that when the Validator enriches the fields during the add, the DOM node wasn't reflecting it. The fix was to replace each field I added with the changes that the validator had added

 _.each($(":input", html), function(field){
          this.validator.addField($(field));//where this.validator is the BootStrapValidator Instacne
          $("#"+$(field).prop("id")).replaceWith(field);
 }, this);

Upvotes: 1

Related Questions