Modify the color of chips when the checkbox is toggled in Materialize CSS

I have been scouring the internet for a solution to my issue.

Currently, I am working with materialize css chips and I am trying to achieve a specific functionality. I want the color of the last chip to turn green and the rest to turn red when a checkbox is checked. When the checkbox is unchecked, all the chips should turn red. I'm not sure if this can be accomplished given my current set of conditions.

$('.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> 

Answer №1

Edit: Modify onChipAdd and onChipDelete events to change the color when a chip is added or deleted.

I want to initialize the chip component without using the jQuery method.

1) Retrieve all the chips.

$(chipInstance[0].$chips)

2) Iterate through each chip and determine if the (index+1) of the chip matches the total number of chips. (Considering indexing starts at zero.)

allChips.each(function(index, element){
  let Color = (index+1) == allChips.length ? 'green' : 'red';
  $(element).addClass(Color)
})

3) Apply a class to change the font color.

Here's a demonstration:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Function call fails when parameters are passed

I've been grappling with this conundrum for a few weeks now, on and off. Perhaps someone else will spot the glaringly obvious thing that I seem to be overlooking. At the present moment, my primary goal is to simply confirm that the function is operat ...

Tips for maintaining the chat scroll position while typing on mobile devices

Check out this example page: https://codesandbox.io/s/summer-flower-uxw47?file=/index.html:4175-4223 The issue at hand is that when accessing the site from a mobile device and tapping on the input field, the keyboard pops up. This causes the text in the m ...

The output is not shown because the form data is not being generated properly by document.getElement

<html> <head> </head> <body style = "text-align:center;" id = "body"> <form id = "number" method="get" name="number"> <input type="text" id="number1" name="number1" value="" /> <input type="text" id="number2" name="nu ...

Preventing users from selecting both future and current dates in a Bootstrap datepicker: A Step-by-Step Guide

Issue Description: I am working on a project using React JS and have implemented the bootstrap datepicker. I have set the input type to "date" for the date of birth field, but I need to restrict users from selecting current or future dates. How can I achie ...

What methods can I use to prevent a JavaScript array from getting filled during page loading?

Looking for assistance to populate an array using JQuery with option values from multiple select elements. I need the array to reset and fill with new options each time a select element is used. Strangely, despite my efforts, the array appears pre-filled w ...

Implementing Content-Security-Policy for a web application embedded in an iframe

Hey there! I've got this cool webapp called myApp, developed using Spring Boot and Vaadin. It's going to be deployed on a Tomcat server at http://tomcatserver:8080/myApp Now, what I want to do is display the webapp in an iframe like this: <if ...

After deploying to Firebase, animations suddenly cease to function

After running npm run-script build and deploying my React app to Firebase hosting with firebase deploy, I encountered an issue where my animations stopped working. I'm puzzled as to why this is happening, especially since I've included keyframes ...

Issues with jQuery tabs "load" function not functioning properly

I created a function that triggers an ajax request onClick and generates a new tab with the loaded data. While it works well, I want to enhance the user experience by loading the tab after the function is complete, eliminating the need for the user to clic ...

The div is set to a position of absolute, causing the overflow-y property to be set to auto. As a

I am facing an issue with a div that has absolute positioning nested inside other divs. If you take a look at the code snippet below from http://jsfiddle.net/d8GYk/, you'll notice the styling properties applied to the div. <div style="position: ...

Guide to modifying the background image color using CSS

Currently, I am attempting to modify the color of an image using CSS. This particular image is a key element in the layout of my website. To get a better understanding, you can view a screenshot of the element here: , and see an example post containing the ...

Create a specific part of a webpage that can be scrolled through

In a unique way, I have designed a page where the only way to navigate is by simply clicking. To achieve this, I have implemented the following custom CSS: body{ overflow:hidden; } However, I have encountered a problem where I am unable to scroll to ...

Why does TypeScript keep throwing the "No inputs were found in the config file" error at me?

Why am I receiving the No inputs were found in config file error from TypeScript? I have set up my tsconfig.json in VS Code, but the error occurs when I try to build it. The terminal displays: error TS18003: No inputs were found in config file '/Use ...

Search through array elements that are nested deeply

Consider the following scenario: an array is provided as input containing various objects with nested elements. The goal is to filter this array in JavaScript and obtain a new array consisting only of objects where the key "navigation" has a value of true. ...

Please confirm the modal by adding a textarea with a newline in SweetAlert2

Every time I attempt to add a line break in the textarea input field, the modal pops up. I have tried adding these lines of code as well, but nothing seems to be working: allowEnterKey: false, focusConfirm: false, Does anyone have any advice for solving ...

The error message "Unexpected token var Node.js" means that there is a syntax error

Currently, I am dealing with Node.js and attempting to present a chart that is created from coordinates in a txt file uploaded to the server. However, I am facing an issue where everything works perfectly when I upload the file on the web page except for t ...

Having trouble with AJAX file uploading in CodeIgniter?

In my codeigniter admin panel, I am working with a table called games which includes an image that I need to upload using ajax. However, I am encountering an issue where the image is not getting uploaded and instead I receive an error stating "no file sele ...

Strategies for resolving a mix of different data types within a single parameter

Here, I am setting up the options params to accept a value that can either be a single string or another object like options?: string[] | IServiceDetail[] | IServiceAccordion[]; However, when attempting to map these objects, an error is encountered: Prope ...

What is the best way to assign an ngModel dynamically using a dot-separated path?

I have noticed a few questions that are similar to this one, but my question has a slight variation. In my controller, I have an object that resembles the following: $scope.data = { foo: {bar: 1, bas: 2}, biz: 3, blat: 4 }; My goal is to c ...

What is the process for importing a JavaScript file into a Vue component?

Having trouble importing JSON results into a Vue component? The results are as follows: [{"id":"d023c5e3-ca3c-4d97-933a-1112a8516eee", "score":9001, "updated":"2018-12-07T13:48:33.6366278", "player":Johanna, "category":Funny}, {"id":"398b65fb-e741-4801-b ...

JavaScript: Specialized gravity diagram

To better understand the issue I am experiencing, please take a look at the image linked below: The concept and problem I am facing is related to creating a weight chart similar to the one shown in the picture or on this site , here is the description of ...