apocalypse
apocalypse

Reputation: 55

jquery .clone() not working

I'm trying to clone a div inside a form. My idea is let users insert multiple entries on my app.

The div .anotacao contain all the fields that user need to make an entry. So by cloning it I can permit users to insert n entries at a time.

<div class="anotacao">
          <div class="field">
            <input id="date" name="date" value="<?=date('d/m/Y');?>" class="date" />
          </div>

          <div class="field">
            <span class="label">às</span>
            <input id="hour" name="hour" value="<?=date('h');?>" class="smallest" />
            <span class="label">:</span>
            <input id="minutes" name="minutes" value="<?=date('i');?>" class="smallest" />
          </div>

          <div class="field">
            <?=form_dropdown('event',$this->entry->list_events(),'','id="event" class="event select"');?>
          </div>

          <div class="field valor">
            <input id="valor" name="valor" value="anotação" class="entry" />
            <span class="show-type"></span>
          </div>

          <div class="field obs">
            <input id="obs" name="obs" value="obs" class="obs" />
          </div>
        </div>

To clone this I have a link with .add-line class in it. When user clicks this link I try to clone the div by calling this JS:

$('.add-line').live('click', function(event){
$('.anotacao').clone().removeClass('anotacao');
return false;

});

It seems all correct but I get no clone or anything. If I delete the clone function and place an alert, for example, the alert is displayed.

Upvotes: 1

Views: 14204

Answers (4)

CalebHC
CalebHC

Reputation: 5042

When you call .clone() it needs to be appended to something. Try this:

$('.add-line').live('click', function(event){
  $('.anotacao').clone().appendTo('#anotacao-container');
  return false;
});

<div id="anotacao-container">
  <div class="anotacao">
  ... fields here      
  </div>
</div>

Upvotes: 6

Teja Kantamneni
Teja Kantamneni

Reputation: 17482

Try appending it

$(this).append($('.anotacao').clone().removeClass('anotacao'));

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 191058

You need to specify where you want it to go with appendTo.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 360016

You have to actually do something with the value returned by .clone(). jQuery does not insert the cloned element into the markup for you.

$('.add-line').live('click', function(event){
    var $source = $('.anotacao');
    $source.clone().removeClass('anotacao').after($source);
    return false;
});

You need to make sure to only select a single div.anotacao to clone each time; otherwise you'll end up with an exponentially-growing number of clones! Whoops, forgot that the removeClass() took care of that!

Upvotes: 1

Related Questions