javascriptphpjqueryhtmlformvalidation.io

php/jQuery - formvalidation, get value of dynamically added inputs


I am trying to use the Formvalidation.io plugin, to dynamically add input fields.

These are my inputs:

<div class="col-lg-4">

    <label class="control-label">Model</label>
    <select name="box[0].model" class="ui dropdown dropdown-model semantic-dropdown">
        <option value="">Choose Model</option>
        <option value="model_one">Model One</option>
        <option value="model_two">Model Two</option>
        <option value="model_three">Model Three</option>
    </select>

</div>

<div class="col-lg-4">
    <label class="control-label">Type</label>
    <select name="box[0].type" class="ui dropdown dropdown-type semantic-dropdown">
        <option value="">Choose Type</option>
        <option value="0">Ingen Konfiguration</option>
        <option value="1">Sommer</option>
        <option value="2">Vinter</option>
    </select>

</div>

<div class="col-lg-4">
    <label class="control-label">Temperatur</label>

    <select name="box[0].temperatur" class="ui dropdown dropdown-temperatur semantic-dropdown">
        <option value="">Choose Temperatur</option>
        <option value="0">No Temperature</option>
        <option value="1">2-8 Grader</option>
        <option value="2">15-25 Grader</option>
        <option value="3">Frozen</option>
    </select>

</div>
<a href="#" class="addButton">Add extra input</a>

And, my template for the hidden fields:

<!-- The template for adding new field -->
<div class="form-group hide" id="bookTemplate">
    <div class="col-lg-4">
        <select name="model" class="ui dropdown dropdown-model semantic-dropdown">
            <option value="">Choose Model</option>
            <option value="model_one">Model One</option>
            <option value="model_two">Model Two</option>
            <option value="model_three">Model Three</option>

        </select>

    </div>
    <div class="col-lg-4">
        <select name="type" class="ui dropdown dropdown-type semantic-dropdown">
            <option value="">Choose Type</option>
            <option value="0">Ingen Konfiguration</option>
            <option value="1">Sommer</option>
            <option value="2">Vinter</option>
        </select>

    </div>
    <div class="col-lg-4">

        <select name="temperatur" class="ui dropdown dropdown-temperatur semantic-dropdown">
            <option value="">Vælg Temperatur</option>
            <option value="0">No Temperature</option>
            <option value="1">2-8 Grader</option>
            <option value="2">15-25 Grader</option>
            <option value="3">Frozen</option>
        </select>

    </div>
    <div class="col-xs-1">
        <button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
    </div>
</div>
<!-- END HIDDEN TEMPLATE-->

Adding the fields and validating them dynamically works like it should. However, I am not seeing the values of the inputs, when the form is submitted: This is the var_dump($_POST) of above:

"array(4) {
  ["box"]=>
  array(3) {
    [0]=>
    string(1) "0"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "1"
  }
  ["model"]=>
  string(0) ""
  ["type"]=>
  string(0) ""
  ["temperatur"]=>
  string(0) ""

The form is submitted using AJAX:

//Submit the form:
$('#bookingform').on('submit', function(e) { 
    e.preventDefault(); //prevent form from submitting
    $form = $(this);
    // Use Ajax to submit form data
    $.ajax({
        url: '/api/submit-form',
        type: 'POST',
        data: $form.serialize(),
        dataType: "json",
        success: function(data) {
            console.log(data.result);
            if (data.result == 'success') {
                console.log(data);
            } else {
                alert('Error #1');
            }
        },
        error: function(data) {
            console.log("ERROR");

        }
    });

});

Running a console.log($form.serialize()); on the form:

box%5B0%5D.model=model_one&box%5B0%5D.type=1&box%5B0%5D.temperatur=1&model=&type=&temperatur=

As you can see, I not getting the values of the box[o].name - furthermore, I am not interested in the input values of the hidden fields, only if they are visible (box[].name)

EDIT: Below is the javascript code for adding the inputs:

bookIndex = 0;
.. code here that is not relevant ..          
// Add button click handler
          .on('click', '.addButton', function() {
              bookIndex++;
              var $template = $('#bookTemplate'),
                  $clone = $template
                  .clone()
                  .removeClass('hide')
                  .removeAttr('id')
                  .attr('data-book-index', bookIndex)
                  .insertBefore($template);

              // Update the name attributes
              $clone
                  .find('[name="model"]').attr('name', 'box[' + bookIndex + '].model').end()
                  .find('[name="type"]').attr('name', 'box[' + bookIndex + '].type').end()
                  .find('[name="temperatur"]').attr('name', 'box[' + bookIndex + '].temperatur').end();

              //Semantic Dropdown - refresh dynamic added dropdowns:
              $('.semantic-dropdown').dropdown();

              // Add new fields
              // Note that we also pass the validator rules for new field as the third parameter
              $('#bookingform')
                  .formValidation('addField', 'box[' + bookIndex + '].model', titleValidators)
                  .formValidation('addField', 'box[' + bookIndex + '].type', isbnValidators)
                  .formValidation('addField', 'box[' + bookIndex + '].temperatur', priceValidators);
          })

However, as stated I can add inputs dynamically, the problem is getting the values from the dynamically added inputs. I can't seem to find this in the formvalidation.io plugin docs either.


Solution

  • I think the matter is in the dataType because you're sending x-www-form-urlencoded not a json data , so try to change the :

    dataType : "html" and add contentType: "application/x-www-form-urlencoded; charset=UTF-8" // set by default

    $.ajax({
        url: '/api/submit-form',
        type: 'POST',
        data: $form.serialize(),
        dataType : "html",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8", 
       ....
    });