MastaBot MastaBot - 5 months ago 14
jQuery Question

How to prevent adding class to more than two element using jquery?

I have table with selectable cells and now I try to prevent selecting more than two cell at once. It should work like that: If I click cell id

4
then it should get class
selected
if next I click cell id
16
then it also should get class
selected
but if next I click cell id
20
then cell id
4
should have removed class
selected
and id
20
should get class
selected
.

I already have something like that jsfiddle

$(".currency-cell").click(function(){
if ($(this).hasClass("selected"))
$(this).removeClass("selected");
else {
$(this).addClass("selected");
}).hover(function(){
$(this).css("background","gold");
},
function(){
if($(this).hasClass("selected"))
$(this).css("background","gold");
else
$(this).css("background","silver");
});

Answer

You need to store id of selected element in array. When td is clicked insert id of it to end of array or if exist in array remove it. If length of array is great than 2 remove first index of array.

var selectedIds = [];
$(".currency-cell").click(function(){
    $(this).toggleClass("selected");

    var id = $(this).attr("id");  
    if (selectedIds.indexOf(id) == -1)
       selectedIds.push(id);
    else   
        selectedIds.splice(selectedIds.indexOf(id), 1);
    
    if (selectedIds.length > 2) {  
        $("#" + selectedIds[0]).removeClass("selected");
        selectedIds.splice(0, 1);
    }       
});
table { 
    width: 200px; 
}
.currency-cell {
    width: 40px;
    height: 40px;
    border: 1px solid silver;
}
.selected { 
    background-color: gold; 
}
.currency-cell:hover { 
    background: gold; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td id="24" class="currency-cell"></td>
        <td id="6" class="currency-cell"></td>
        <td id="4" class="currency-cell"></td>
        <td id="14" class="currency-cell"></td>
    </tr>
    <tr>
        <td id="1" class="currency-cell"></td>
        <td id="7" class="currency-cell"></td>
        <td id="8" class="currency-cell"></td>
        <td id="22" class="currency-cell"></td>            
    </tr>
    <tr>
        <td id="27" class="currency-cell"></td>
        <td id="30" class="currency-cell"></td>
        <td id="28" class="currency-cell"></td>
        <td id="29" class="currency-cell"></td>
    </tr>
</table>

You can test it on full of your html in jsfiddle