简体   繁体   中英

dynamically add, validate and remove sets of form fields

I'd like to create a webpage where the user can add and remove sets of form fields by means of one add button and remove buttons related to the set to be removed. Entered values will be checked by means jquery validate, for which rules are added dynamically as well. pls see an an simplified example below of my targeted form:

What is a good structure of javascript code for adding, removing and validate sets of forms fields? I googled -also on this site- and there are many javascript examples for adding sets of formfields. I like the example I found at view-source: http://www.coldfusionjedi.com/demos/jqueryvalidation/testadd.cfm , which uses a form template. But I struggle in particular with the javascript coding for the removing buttons..(which are not in the example)

my targeted (simplified) form (template with 1 set of 3 formfields):

<form name="myForm" id="myForm" method="post" action="">
  <input id="name1" name="name1" />
  <input id="email1" name="email1" />
  <input id="phone1" name="phone1" />
  <input type="submit" value="Save">
</form>

I think that you should template the form. Ie wrap it in a function, so you can create it again and again. Here is a jsfiddle http://jsfiddle.net/krasimir/2sZsx/4/

HTML

<div id="wrapper"></div>
<a href="#" id="add-form">add form</a>

JS

var wrapper = $("#wrapper");
var addForm = $("#add-form");
var index = 0;

var getForm = function(index, action) {
    return $('\
        <form name="myForm" id="myForm" method="post" action="' + action + '">\
          <input id="name' + index + '" name="name' + index + '" />\
          <input id="email' + index + '" name="email' + index + '" />\
          <input id="phone' + index + '" name="phone' + index + '" />\
          <input type="submit" value="Save">\
          <a href="#" class="remove">remove form</a>\
        </form>\
    ');
}

addForm.on("click", function() {
    var form = getForm(++index);
    form.find(".remove").on("click", function() {
       $(this).parent().remove();
    });
    wrapper.append(form);
});

Simple validation can be done when your form is submitted, thus:

$('#myForm').submit({
    var n1 = $('#name1').val();
    var e1 = $('#email1').val();
    var p1 = $('#phone1').val();

    if (n1=='' || e1=='' || p1=='') {
        alert('Please complete all fields');
        return false;
    }
});

Note that the return false will abort the submit and return user to the document.


Great code for adding/removing form fields can be found in this question: https://stackoverflow.com/questions/18520384/removing-dynamically-generated-textboxes-in-jquery

jsFiddle here

If you are using KeenThemes (maybe Metronic theme) https://preview.keenthemes.com/good/documentation/forms/formvalidation/advanced.html

You can do like this.

var form = document.getElementById('form_id');
var validator = FormValidation.formValidation(
  form,
  {
      fields: {
          name: {
              validators: {
                  notEmpty: {
                      message: 'Please enter template name'
                  },
                  stringLength: {
                      min: 3,
                      trim: true,
                      message: 'Please enter a longer  name.'
                  },
              }
          },
          ...
            more fields here
          ...
      },
      plugins: {
          trigger: new FormValidation.plugins.Trigger(),
          bootstrap: new FormValidation.plugins.Bootstrap(),
      },
  });


function addNewFieldDynamically() {
    // add new field here
    ...
    validator.addField('field_name', {
        validators : {...}
    })
}

function removeFieldDynamically() {
    // remove a field here
    ...
    validator.removeField('field_name')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM