Reputation: 26344
I am replacing a span inside a table > td with option box. I want to assign some unique id with dynamic value while creating the option box. How to achieve this?
Unique id is already generated , I want to set this unique id in Html while creation.
<td id="tdTest">
<span id="spanId" class="connectedSlot" style="color:rgb(27,99,173)">Enabled</span>
</td>
$("#"+spanId).replaceWith(function () {
return "<select class='form-control' id=<<DYNAMIC ID>> style='width:200px;'><option value='0'>Enabled</option><option value='1'>Disabled</option></select>";
});
For example , I will get some value from and assign to a variable and later assign this variable to id.
var myId = "OptionId"+test;
select class='form-control' id=myId style='width:200px;'>
Thanks
Upvotes: 0
Views: 15049
Reputation: 11
It's been several years since this was posted, and the accepted solution didn't work for me. Here is the syntax that did:
[id]="unqiueID"
Upvotes: 0
Reputation: 395
Use a variable within a string like this:
var unqiueID = "myID123", ret = "";
ret = "<select class='form-control' id='" + unqiueID +"' style='width:200px;'>";
Upvotes: 1
Reputation: 744
Possible Solution:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
Look into these Questions for others: link link
Upvotes: 0
Reputation: 31851
One possible way to ensure that a unique value is assigned is to keep track of all the available id's and assign an id which isn't there in our list.
getUniqueId()
is a function that will always return a unique id.
function getUniqueId() {
//get all the ids in this document
var ids = new Array();
$('[id]').each(function() { //Get elements that have an id=
ids.push($(this).attr("id")); //add id to array
});
//give some random value to uniqueId
//if this value is in ids array, then assign a different id and recheck the condition
var uniqueId;
while(true) {
uniqueId = 'some-prefix-' + Math.floor(Math.random() * 10000);
if($.inArray(uniqueId , ids) == -1) {
break;
}
}
return uniqueId;
}
Upvotes: 0