Reputation:
When I click on my button I am trying to create a bootstrap label. But each time I click it should start off at label-default and work through the switch until it gets to the last one the go back to the beginning
As shown on image below it not starting off at label-default
Question each time I click on the button to create label how can I make sure it does not double up and starts from label-default
DEMO
SCRIPT
$(document).on('click', '#category_button', function(e){
e.preventDefault();
//if ($("#label-" + category_name).length == 0) {
var rand = Math.floor((Math.random() * 5) + 1);
switch(rand){
case 1:
element = 'label-default';
break;
case 2:
element = 'label-primary';
break;
case 3:
element = 'label-success';
break;
case 4:
element = 'label-info';
break;
case 5:
element = 'label-warning';
break;
}
html = '';
html += '<li id="">';
html += '<span class="label ' + element + '">';
html += 'Hello';
html += '</span>';
html += '</li>';
$('.categories ul').append(html);
//}
});
Upvotes: 1
Views: 295
Reputation: 1
You can use an array, Array.prototype.slice()
, Array.prototype.splice()
to create a copy of original array. If copied array has .length
equal to 0
remove first element from array, set the element as element
value, else get, set random element from copied array as element
value, repeat procedure.
var arr = ["default", "primary", "success", "info", "warning"];
var label = "label-";
var copy = [];
$(document).on("click", "#category_button", function(e) {
e.preventDefault();
var element, rand;
if (!copy.length) {
copy = arr.slice(0);
element = copy.splice(0, 1);
} else {
rand = Math.floor(Math.random() * copy.length);
element = copy.splice(rand, 1);
}
var html = $("<li>", {
"id":"",
"html":$("<span>", {
"class": label.slice(0, -1).concat(" ", label, element),
"html": label + element
})
});
$(".categories ul").append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button id="category_button">click</button>
<div class="categories">
<ul>
</ul>
</div>
codepen http://codepen.io/anon/pen/PpXryW
Upvotes: 2
Reputation: 53119
Not sure if I misunderstood your question, but you are using a random to decide which label to add. If you want an ordered sequence, you should not be using random. Code shown below:
var counter = 0;
$(document).on('click', '#category_button', function(e){
e.preventDefault();
switch(counter) {
case 0:
element = 'label-default';
break;
case 1:
element = 'label-primary';
break;
case 2:
element = 'label-success';
break;
case 3:
element = 'label-info';
break;
case 4:
element = 'label-warning';
break;
}
counter = (counter + 1) % 5;
var html = '';
html += '<li id="">';
html += '<span class="label ' + element + '">';
html += 'Hello';
html += '</span>';
html += '</li>';
$('.categories ul').append(html);
//}
});
Upvotes: 1