Add/Remove Input Fields Dynamically with jQuery

by Renilson Meneguci

HTML

<form role="form" action="/wohoo" method="POST">
  <label>Stuff</label>
    <div class="multi-field-wrapper">
      <div class="multi-fields">
        <div class="multi-field">
            <select class="dependent" name="products" multiple>
    <optgroup label="C1">
        <option>P1A</option>
        <option>P1B</option>
        <option>P1C</option>
    </optgroup>
    <optgroup label="C2">
        <option>P2A</option>
        <option>P2B</option>
        <option>P2C</option>
    </optgroup>
    <optgroup label="C3">
        <option>P3A</option>
        <option>P3B</option>
        <option>P3C</option>
    </optgroup>
</select>
        </div>
      </div>
    <button type="button" class="add-field">Add field</button>
  </div>
</form>

JavaScript

$('.multi-field-wrapper').each(function() {
    var $wrapper = $('.multi-fields', this);
    $(".add-field", $(this)).click(function(e) {
        $('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
    });
    $('.multi-field .remove-field', $wrapper).click(function() {
        if ($('.multi-field', $wrapper).length > 1)
            $(this).parent('.multi-field').remove();
    });
});

$(function () {
    $("select.dependent").each(function (i, sel) {
        var original = $(this).clone(),
            dependent = $("<select></select>").attr({
                name: this.name,
                multiple: true
            }).insertAfter(this)
            this.name = "categories_" + this.name

            $("optgroup", this).replaceWith(function () {
                return "<option>" + this.label + "</option>"
            })
            $("option:first",this).prop("selected",true)
            $(this).removeAttr("multiple").on("change", function () {
                var cat = $(this).val()
                dependent.html(original.children("[label='" + cat + "']").html())
            }).change()
            console.log(this)
    })
})