1

I have set up the following JSFiddle

My application has several .formContent rows, I am only displaying one row in the fiddle.

What I am trying to do is duplicate the div with the class .labelAndInput if the checkbox is checked, and place a new one underneath.

The new divs label and input should have the same id/name as the one copied, but with "testing" on the end of them.

At the moment I am trying something like this which does not seem to do anything :

$(function() {
  $('input:checkbox[name=label1Newline]').change(function() {
    if ($(this).checked) {
          $(this).parent().siblings(".labelAndInput").clone().insertAfter("div.labelAndInput:last");
    }
  });
});

How can I clone the div, change the ids/names to include testing, and then append it?

Thanks

3
  • change $(this).checked with $(this).prop("checked"). It works: jsfiddle.net/vt2czgse/43 Commented Feb 24, 2016 at 17:27
  • or with this.checked :) Commented Feb 24, 2016 at 17:28
  • He is using jQuery, so my recommendation is with jQuery :) Commented Feb 24, 2016 at 17:28

1 Answer 1

3

Working fiddle

You should replace :

if ($(this).checked) {

By :

if ( $(this).is(':checked') ){
//OR
if ( this.checked ){

NOTE : The new divs label and input should have the same id/name, Be careful the id should be unique in the same document.

Hope this helps.

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

8 Comments

Yes, his code is full of bugs even in a 5 lines code, but this solves the problem that OP asking for
My comment here was a response to other user that said the code is full of bugs, but he removed the comment LOL
Thanks, that seemed to work. Is my code full of bugs? Additionally, is there any way to change the name and id of the cloned element? Thanks
You're welcome, you want every time the checkbox checked to add one labe+input or like the current code add 1 in first time 2 second check...?
IMO better to separate model that will be cloned every time in the end of the page then before insert it in the last position (just after new line checbox) change the id like you want check the following fiddle jsfiddle.net/vt2czgse/44.
|

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.