I have the code below:
var classCode = "";
var colorUsed = [];
var classes = [];
var color = ["yellow", "lightblue", "lightgreen", "pink", "orange", "cyan", "lightgrey", "plum", "wheat", "khaki"];
function colorClass(row) {
classCode = $(row).html();
var index = -1;
if (colorUsed.length != 0) {
index = classes.indexOf(classCode);
} else {
index = -1;
}
while (index == -1) {
colorNum = Math.floor((Math.random() * 10));
if (!(color[colorNum] in colorUsed)) {
colorUsed.push(color[colorNum]);
classes.push(classCode);
index = 1;
} else {
alert("same color!");
index = -1;
}
}
if (index != -1) {
colorNum = classes.indexOf(classCode);;
}
$(row).css("background-color", colorUsed[colorNum]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
<th>Savings for holiday!</th>
</tr>
</thead>
<tbody>
<tr><td colspan="3" onclick="colorClass(this);">ClassA</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassC</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassD</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassE</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassF</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassG</td></tr>
<tr><td colspan="3" onclick="colorClass(this);">ClassH</td></tr>
</tbody>
</table>
I use "in" function to avoid same color to apply, but it is not working, I know there is another way to use which to loop the element one-by-one and compare it, but I don't like to use that.
Or any other way to detect it? Since there is no hashset in javascript, is it possible to implement in Jquery?
Array.indexOf()- that will remove the need for your first check and the laterinindexOf(), notin. Your code is most likely throwing at least one syntax error asinis not intended to be used as you are