Search code examples
javascriptjqueryclone

jQuery: Clone element by choosing SELECT OPTION


I have a SELECT where I choose how many cars the user has. After that he/she will get the same amount of DIVs with INPUTs to descripe what models etc.

How do I clone the DIV with the containing INPUTs, with the SELECT?


Solution

  • This should give you the general idea...

    $('select#cars').change(function() {
       // Get number of cars chosen
       var carsCount = $(this).val(),
           // Get a reference to the first input group so we can clone it
           carInput = $('#car-inputs div:first');
    
       // Clone per number chosen
       for (var i = 0; i < carsCount; i++) {
           // Insert clone after original.
           // IRL, you probably need to do some preprocessing on it first.
           carInput.clone().insertAfter(carInput);
       }
    });