I want to choose a random ID from the list of available IDs. After choosing, I want to check if there is an item with that ID, if there is no, then I want to add there. If it exists then I want to generate the ID again till it chooses an ID which does not exist.
Problem:
Currently I'm using if statement
to check if an ID exists, if it exists then it generates again. However the problem is that it only checks once.
It is possible that newly chosen ID also exists, therefore I would like to keep checking until it finds some ID which doesn't exist. For that I would need to use a loop, but I'm unable to figure out how to do that because the items are added dynamically.
Here's what I have tried:
HTML:
<input type="button" id="button" value="Add new" />
<ul class="items">
<li id="a4">item with id a4</li>
<li id="c2">item with id c2</li>
<li id="c3">item with id c3</li>
<li id="a1">item with id a1</li>
</ul>
Javascript:
function randID () {
var arr = new Array("c1", "c2", "c3", "c4", "a1", "a2", "a3", "a4","a5","a6");
var index = Math.floor(Math.random()*(arr.length));
return arr[index];
}
$('#button').click(function() {
var newID = randID();
if ( $('.items').find('#'+newID).length > 0 ) {
var newID = randID();
}
$('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');
});
JSFiddle: https://jsfiddle.net/o4uL6gaj/