I have searched online and I couldn't get a solution to my problem.
I am working with materialize css chips, what I want is that whenever the checkbox is checked, the color of the last chip should change to green and others to red, when unchecked,they all turn red.
I don't know if this is possible as I have set my conditions already
$('.chips-placeholder').chips({
placeholder: 'Enter options',
secondaryPlaceholder: '+Options',
limit:6
});
$(document).ready(function() {
$('#anscheck').change(function() {
if($("#anscheck").is(":checked")){
}
});
});
html
<div class="row opt">
<div class="col m4 s10 offset-m3 chips-placeholder">
<input type="text" name="opts[]">
</div>
<div class="col m4 s10 switch correctans">
<label>
Off
<input type="checkbox" id='anscheck'>
<span class="lever"></span>
On
</label>
</div>
</div>
Edit: Set onChipAdd
and onChipDelete
events to change the color when adding or deleting a chip.
I would initialize the chip component without jQuery method.
1) Get all of the chips.
$(chipInstance[0].$chips)
2) Loop through all the chips and check if the (index+1) of the chip equals the number of all chips. (Cause index is zero-based.)
allChips.each(function(index, element){
let Color = (index+1) == allChips.length ? 'green' : 'red';
$(element).addClass(Color)
})
3) Add class to change the font color.
Here's a demo:
let target = $('.chips-placeholder');
let options = {
placeholder: 'Enter options',
secondaryPlaceholder: '+Options',
limit: 6,
onChipAdd: function(){
CheckChipsColor();
},
onChipDelete: function(){
CheckChipsColor();
}
}
let chipInstance = M.Chips.init(target, options)
$('#anscheck').change(function() {
CheckChipsColor();
});
function CheckChipsColor(){
let allChips = $(chipInstance[0].$chips);
allChips.removeClass('red green');
if ($("#anscheck").is(":checked")) {
allChips.each(function(index, element){
let Color = (index+1) == allChips.length ? 'green' : 'red';
$(element).addClass(Color)
})
}
}
.red{
color: red;
}
.green{
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.js"></script>
<div class="row opt">
<div class="col m4 s10 offset-m3 chips-placeholder">
<input type="text" name="opts[]">
</div>
<div class="col m4 s10 switch correctans">
<label>
Off
<input type="checkbox" id='anscheck'>
<span class="lever"></span>
On
</label>
</div>
</div>