Question User
Question User

Reputation: 2293

JQuery clone is not working with class selector

Fiddle

I am trying to clone a span from the onClick() function of a button. First time this works fine but when I try second time it is not cloning. What am I doing wrong?

Here is the essence of my code.

$(document).ready(function(){
    $('.addmachinerow').on('click',function(){

    var edcname =  $('.edc_name option:selected').val();
    var machine_description =   $("input[name='machine_description'").val();
    var capacity =   $("input[name='capacity'").val();
    var voltage_level =   $("input[name='voltage_level'").val();
    var powertype =  $("select[name='typeofpower'").val();
    var edcautovalue = $('.ecaddingspan').attr('data-value');

//if($('#bank_increment').html() == '')  $('#bank_increment').html('0');   else  $('#bank_increment').html(parseInt($('#bank_increment').html())+1);

//if($('#bank_clickededit').html() == '') var bank_increment =  $('#bank_increment').html(); else  var bank_increment = $('#bank_clickededit').html();


$('.ecaddingspan').clone().appendTo('.edcparent');
//$('.bankname, .bankbranch , .IFSCcode , .bankaccno , .accsincefrom').val('');

 var edc_details = {'edcname' : edcname, 'machine_description' : machine_description, 'capacity' : capacity, 'voltage_level' : voltage_level, 'powertype' : powertype }
//$('.bank_details_array').append(JSON.stringify(bank_details)+'&&');
    });
});

Additionally:

How can i clone the entire sets on clicking the Total clone button ?

I need to save the values in array with different names. Is that possible ?

Upvotes: 2

Views: 1898

Answers (3)

Vanquished Wombat
Vanquished Wombat

Reputation: 9525

The issue is a common misconception of JQuery selectors. If you play with ID selectors then switch to class selectors then you often don't notice a difference in behaviour. The ID selector doc says

ID Selector: If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM

whilst for the class selector

Class Selector: Selects all elements with the given class.

What this means is that when you clone the target element you get away with a subsequent ID selection (JQuery ignores the duplicates) but a subsequent class selection will trip you up if you were not expecting JQuery to return multiple matches. Class selectors are great for grouping elements but not so great for cloning.

While I am on the soap box - whenever you use the clone function you should consider and fix the potential duplicate ID and un-required class duplicates that you are producing. Duplicate ID's are definitely bad show - duplicate classes may actually be by design but you should still consider them.

In the code sample below I assign the class iAmSpartacus to the original span which the onClick() function then clones. Each clone also gets the iAmSpartacus class so I remove it from each new clone to ensure that the $(".iAmSpartacus") selector always returns a maximum of one element. The spans show their current class property to prove the point.

// this runs one - shows us classes of original span
var origSpan=$(".iAmSpartacus")
origSpan.html("My classes are: " + origSpan.prop("class")) 

$("#daButton").on("click", function(e) {
  
  var newSpan = $(".iAmSpartacus").clone();
  newSpan.removeClass("iAmSpartacus");  // remove the dup targetting class
  newSpan.appendTo('.edcparent');
  newSpan.html("My classes are: " + newSpan.prop("class")) 
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="daButton">Click me</button>
<div class="edcparent" style="border: 1px solid red;">
    <span class="ecaddingspan iAmSpartacus" style="display: block;">I am a span</span>  
</div>

Upvotes: 0

Sarika Koli
Sarika Koli

Reputation: 783

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
   
       $('.cloneitem').not('.cloned').clone().addClass('cloned').appendTo('body');
    });
});
</script>
</head>
<body>

<p class="cloneitem">This is a paragraph.</p>

<button>Clone all p elements, and append them to the body element</button>

</body>
</html>

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

How can i clone the entire sets on clicking the Total clone button ?

You've to use event delagtion on() instead :

$('body').on('click','.addmachinerow', function(){
   //Event code
})

Since the new .addmachinerow added to the page dynamically after the clone.

I need to save the values in array with different names is that possible ?

I suggest the use of the array name [] like :

<input name='machine_description[]' />
<input name='voltage_level[]' />

Hope this helps.

Upvotes: 5

Related Questions