Search code examples
javascriptjqueryjquery-events

Add multiple inputs dynamically


I have a form with two inputs where, when the user selects a description from the datalist the second input is filled with the product. It works fine -> bootbly1

Now I want to add dynamically inputs in the form. The inputs are inserted fine but the above function doesn't apply to the new inputs..

Here is the final bootbly

<div class="container">
  <div class="row">
            <div class="col-lg-12 col-xs-12">
            <form id="bookForm" action="#" method="post" class="form-horizontal">
            <div class="form-group">
                <div class="col-xs-4">
                    <input class="form-control" name="description-0" id="ajax" list="json-datalist" placeholder="Description" type="text">
                    <datalist id="json-datalist"></datalist>
                    
                </div>
                <div class="col-xs-2" style="width: 160px;">
                    <input class="form-control" name="product-0" placeholder="product" type="text">
                </div>
                
                 <div class="col-xs-1">
                    <button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
                </div>
            </div>   
           
            <!-- The template for adding new field -->
            <div class="form-group hide" id="bookTemplate">
                 <div class="col-xs-4">
                    <input class="form-control" name="description" id="ajax" list="json-datalist" placeholder="description" type="text">
                    <datalist id="json-datalist"></datalist>
                    
                </div>
                <div class="col-xs-2" style="width: 160px;">
                    <input class="form-control" name="product" placeholder="product" type="text">
                </div>
                
                
                <div class="col-xs-1">
                    <button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
                </div>
            </div>

            <div class="form-group">
                <div class="col-xs-5 col-xs-offset-1">
                    <button type="submit" class="btn btn-default">Submit</button>
                </div>
            </div>
        </form>


            </div>
        </div>
  </div>

and the JavaScript:

var counter = 0;    
var dataList = document.getElementById('json-datalist');
    
    var jsonOptions = [{
                        "product": "11111",
                        "description": "description 1"
                      }, {
                        "product": "22222",
                        "description": "description 2"
                      }, {
                        "product": "33333",
                        "description": "description 3"
                      }, {
                        "product": "44444",
                        "description": "description 4"
                      }, {
                        "product": "55555",
                        "description": "description 5"
                      }]; 

    jsonOptions.forEach(function(item) {
                    
      var option = document.createElement('option');
      
      option.value = item.description;
      option.text = item.description;
      option.setAttribute('data-product', item.product);
      dataList.appendChild(option);
    });

$(function() {
    $('#ajax').change(function() {
        var description = $(this).val();
        var product = $('#json-datalist > option[value="' + description + '"]').data('product');
        $('input[name=product-'+ counter + ']').val(product);
        
    });
});

    
$('#bookForm')
    // Add button click handler
    .on('click', '.addButton', function() {
        counter++;
        var $template = $('#bookTemplate'),
            $clone    = $template
                            .clone()
                            .removeClass('hide')
                            .removeAttr('id')
                            .attr('data-book-index', counter)
                            .insertBefore($template);

        // Update the name attributes
        $clone
            .find('[name="description"]').attr('name', 'description-' + counter).end()
            .find('[name="product"]').attr('name', 'product-' + counter).end();
    })

    // Remove button click handler
    .on('click', '.removeButton', function() {
        var $row  = $(this).parents('.form-group'),
            index = $row.attr('data-book-index');

        // Remove element containing the fields
        $row.remove();
    });

One more thing is that if the user presses some times the plus button to create inputs and then tries to fill the first one, then the last input will be filled..


Solution

  • Basically, your selector for dynamic descriptions ("#ajax") and counter (taking the last modified counter) to update product were wrong.

    Solution: http://www.bootply.com/ZckX8mlKOQ