Ryan Hipkiss Ryan Hipkiss - 1 month ago 10
HTML Question

Duplicate input on click, insert before clicked element - jQuery

I have markup like so:



$('label.duplicate').click(function(e) {
e.preventDefault();
var _for = $(this).attr('for');

$('input[name="' + _for + '"]').clone().insertBefore($(this));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input_one[]">
<label class="duplicate" for="input_one[]">Add another car</label>





This doesn't duplicate, or provide an error so I don't know why this is not working?

Answer

It is working, but you need to wait for the dom-structur to load before you run you code. Put everything inside documet.ready like this:

$(document).ready(function() {
  $('label.duplicate').click(function(e) {
    e.preventDefault();
    var _for = $(this).attr('for');

    $('input[name="' + _for + '"]').clone().insertBefore($(this));
  });
})

Or insert your code dead last on you page. Read more about this here: https://learn.jquery.com/using-jquery-core/document-ready/