Search code examples
jqueryhtmlclone

jQuery, get all the values of all cloned input fields


Need some help or pointers to achieve the following. Cloning input fields on click and retrieving the values of the fields on change so they get pasted as text into another div. However it only seems to work for the original hard coded fields (not the cloned ones). I have tried adding each function on several places in the code but with to no avail. My code looks like this for now:

<div class="cartWrapper">
    <div class="clonedInput">

        <label for="chipsCategory" class="">Chips Category <span class="requiredField">*</span></label>
        <select class="categoryName1 changeFields" name="chipsCategory">
            <option value="Kraks">Kraks</option>
            <option value="Curls">Curls</option>
            <option value="Crisps">Crisps</option>
        </select>

        <label for="chipsTaste" class="">Choose Taste <span class="requiredField">*</span></label>
        <select class="chipsTaste1 changeFields" name="chipsTaste">
            <option value="brand_1">Brand 1</option>
            <option value="brand_2">Brand 2</option>
            <option value="brand_3">Brand 3</option>
        </select>

        <label for="chipsQty">Quantity <span class="requiredField">*</span></label>
        <input type="number" value="1" class="changeFields chipsQty" name="chipsQty[">


    </div>

      <button class="clone">Clone</button> 

    </div>
</div>    
<div id="pasteItems"></div>

and the js:

$( document ).ready(function() {

    function clone(){

        $('.clonedInput:first')
        .clone()
        .appendTo(".cartWrapper")
        .each(function(){})
        .on('click','button.clone',clone).append('<button class="remove">Remove</button>')
        .on('click','button.remove',remove);        
}

function remove(){
    $(this).parents(".clonedInput").remove();
}

$("button.clone").on("click", clone);

$("button.remove").on("click", remove);


function getValues() {

    var categoryName = $('.categoryName1').val();

    var chipsTaste = $('.chipsTaste1').val();

    var chipsQty = $('.chipsQty').val();    

    $('#pasteItems').text(categoryName + ' ' + chipsTaste + ' ' + chipsQty);

}

getValues();

$('.changeFields').change(function(){

$(this).each(function(){

    getValues();

    });

});


});

Thank you very much for all help!


Solution

  • Since they were created dynamically, they cannot be selected in the same way (see Delegation). So you need :

     $(".cartWrapper").on('change', '.changeFields', function() {
         //do what you need to with the value of the cloned input
      });