0

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?

4
  • its working ... Commented Oct 27, 2016 at 10:54
  • your code already working good Commented Oct 27, 2016 at 10:56
  • Yeah, I'm not sure whats blocking it my end - I see it working on here. Bizzare. Commented Oct 27, 2016 at 10:56
  • is the label generated dynamically? That might be the problem if the on click listener executes prior to appending the label in the page Commented Oct 27, 2016 at 14:42

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, after the edits I see it working on here. I have it run in a document ready.
0
<input type="text" name="input_one[]">
<label class="duplicate" for="input_one[]">Add another car</label>

just .duplicate is enough to duplicate:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.