To link the label with the radio, instead of using a JS variable to maintain, you could generate a unique ID like a GUID, and use it directly.
When deleting the block, no need to have the ID, because you have the close HTMLElement that is inside the block, you can use parent() function and remove() function to do the job.
Here is an example:
/**
* Generate a guid part
*/
function GuidPart()
{
return Math.floor(Math.random() * 0x10000).toString(16);
}
/**
* Generate a new GUID
*/
function getGuid()
{
return (GuidPart() + GuidPart() + "-" +
GuidPart() + "-" +
GuidPart() + "-" +
GuidPart() + "-" +
GuidPart() + GuidPart() + GuidPart());
}
/**
* Build a new block with radio, label and close span
*/
function buildNewRadio(labelText)
{
// Retrieve a new guid
var guid = getGuid();
// Create a span container with the radio and label inside
// linked together by the guid
var container = $(document.createElement("span")).append(
$(document.createElement("input")).attr('id', guid),
$(document.createElement("label")).attr('for', guid).val(labelText))
.addClass("container");
// Finally append the close span (use to remove the entiere block)
container.append(
$(document.createElement("span").addClass("close")
.click(function(mouseEvent) {
// Retrieve the span container and remove it
$(this).parent().remove();
}));
return container;
}
You can call the buildNewRadio function and attach the result HTMLElement to your DOM container