--- layout: default title: Adding dynamic field permalink: /examples/adding-dynamic-field/ ---

Adding dynamic field


{% include share.html %}

When working with complex form, the fields might be added to (or remove from) the form dynamically. The newly added fields also need to be validated.

This example demonstrates a sample scenario where you have to solve validating dynamic fields problem.

Before going to the details, there are some methods and events you need to know:

Method/Event Description
addField() method Adding new field
removeField() method Removing given field
added.field.fv event Called after adding new field
removed.field.fv event Called after removing given field

Adding fields with same names

Assuming that you are managing a survey which consists of a question and some options that user can choose from. The form allows you to add more options but the number of options can't exceed 5.

{% include demo/tabs.html id="same-name" frameworks="bootstrap" dir="same-name" codes="programmatic" %}

Adding fields with different names

The following form manages the wish list of books you would love to buy. Each book must have three properties which are title, ISBN number and price (in dollar).

Assume that, due to the required naming convention from server, the fields for these properties are named as book[i].title, book[i].isbn and book[i].price, where i is the index number of book which can be 0, 1, 2, and so forth.

The example uses the row option to indicate the field container when using multiple fields in the same row
{% include demo/tabs.html id="different-name" frameworks="bootstrap" dir="different-name" codes="programmatic" %}

Using other plugin for added fields

Sometime, the added fields aren't just simply a normal input such as text box, text area. They can be used with other plugins such as a date picker, an auto-completed control, etc.

In this case, the field should be initially as a normal text input, and then integrated with other plugin after being added.

The following sample code attaches a date picker to newly added input by triggering the added.field.fv event:

{% highlight javascript %} $('#taskForm') .formValidation({ ... }) .on('added.field.fv', function(e, data) { // data.field --> The field name // data.element --> The new field element // data.options --> The new field options if (data.field === 'dueDate[]') { // The new due date field is just added // Create a new date picker data.element .parent() .datepicker({ format: 'yyyy/mm/dd' }) .on('changeDate', function(evt) { // Revalidate the date field $('#taskForm').formValidation('revalidateField', data.element); }); } }); {% endhighlight %}
You should look at the basic principles when integrating FormValidation with other plugins
{% include demo/tabs.html id="using-other-plugin" frameworks="bootstrap" dir="using-other-plugin" codes="programmatic" %}

Related examples