Reputation: 3755
What would be a good strategy for dealing with duplicated id's when using jquery clone method? For example, i need to clone a button in a unspecified number of times. Which is the best way for generating unique id's and keep track of it?
<div id="button-pool">
<button id="bt1" class="return">Button</button>
</div>
$(document).ready(function(){
$("#bt1").click(function(){
var newButton = $(this).clone();
$("#button-pool").append(newButton);
});
});
Upvotes: 3
Views: 2610
Reputation: 501
$(document).ready(function(){
$("body").on('click','#bt1',function(){
var newButton = $(this).clone();
$("#button-pool").append(newButton);
});
});
Upvotes: 0
Reputation: 16821
You can use an Attribute StartsWith Selector to see how many buttons with that same id naming style already exists:
"button[id^='bt']"
And append it increasing it by 1
:
$(document).ready(function(){
$("#bt1").click(function(){
var idcount = $("button[id^='bt']").length;
var newButton = $(this).clone();
newButton.attr("id", "bt" + (idcount + 1));
$("#button-pool").append(newButton);
});
});
.return{
background-color: yellow;
}
#bt1{
border: 2px solid navy;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="button-pool">
<button id="bt1" class="return">Button</button>
</div>
Upvotes: 3
Reputation: 39004
You can use a simple counter, and append it to the button id. This counter should be inside a closure not to interfere with the rest of the scripts in your page;
$(document).ready(function(){
var btnId = 1; // This is a safe place, inside a closure (function body).
$("#bt1").click(function(){
var newButton = $(this).clone();
newButton.attr('id','btn' + btnId);
btnId++; // Increment after creating each new button
$("#button-pool").append(newButton);
});
});
You can also create the buttons without ids, unless you really need them. Why do you need to keep track of them?
Upvotes: 0
Reputation: 894
Utilizing Classes to acheive this is a much better strategy, bloating your DOM with generated ID's is not really a great idea. (Poor Design Practice)
<div id="button-pool">
<button class="btns" custom-attr='1' class="return">Button</button>
</div>
$(document).ready(function(){
$(".btns").click(function(){
var newButton = $(this).clone();
newButton.attr('custom-attr', parseInt(newButton.attr('custom-attr'))+1);
$("#button-pool").append(newButton);
});
});
You can also use custom attributes to track your buttons so that they're still unique from one another, but they don't really need to have ID's
Upvotes: 3
Reputation: 2915
Something like this should work
var count = 0;
$("#bt1").click(function(){
var newButton = $(this).clone();
newButton.attr("id", "bt"+count);
$("#button-pool").append(newButton);
count++;
});
Upvotes: 0