I have 8 divs and when you click on a div it gets selected and its value will be added to an array. Once you select 5 divs the others will be set to "not selected" and you can't select any more divs. Now what I want is if you click on a selected div I want to remove the select feature from it and have its value removed from the array but my method is not working. How can I achieve this? Thanks in advance.
let testArray = []
$('.none').on('click', function() {
if (testArray.length < 4) {
testArray.push($(this).find('p').html())
$(this).removeClass('none')
$(this).addClass('selected')
} else if (testArray.length == 4) {
testArray.push($(this).find('p').html())
$(this).removeClass('none')
$(this).addClass('selected')
console.log(testArray)
$('.test').removeClass('none')
$('.test:not(.selected)').addClass('notSelected')
}
})
//not working
$('.selected').on('click', function() {
var filteredArray = testArray.filter(function(e) {
return e !== $(this).find('p').html()
})
testArray = filteredArray
$(this).removeClass('selected')
$('.test').removeClass('notSelected')
$('.test:not(.selected)').addClass('none')
console.log(testArray)
})
body {
display: flex;
flex-direction: row;
justify-content: space-evenly;
}
.test {
display: flex;
width: 100px;
height: 100px;
border: 2px solid transparent;
background-color: #000000;
margin-left: 2%;
}
.selected {
border: 2px solid green;
cursor: pointer;
}
.notSelected {
border: 2px solid red;
cursor: default;
}
.none:hover {
cursor: poiner;
}
.test p {
color: #ffffff;
margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test none">
<p>test1</p>
</div>
<div class="test none">
<p>test2</p>
</div>
<div class="test none">
<p>test3</p>
</div>
<div class="test none">
<p>test4</p>
</div>
<div class="test none">
<p>test5</p>
</div>
<div class="test none">
<p>test6</p>
</div>
<div class="test none">
<p>test7</p>
</div>
<div class="test none">
<p>test8</p>
</div>