How can I add styling to materializecss chip elements?

When working with tags on a web page, Materializecss makes it easy. However, I have a requirement where the tags need to be of different colors based on their types. Although this is feasible, another complication arises when supporting Materializecss keyboard functions.

Prior to this, I resorted to a hack by manually adding div elements with a class "chip" for tags. Now, I am using the materialize addChip function, which only accepts 'tag' and 'data' as parameters.

The challenge now is how to specify color and textcolor classes for these chips when creating them dynamically in JavaScript using:

instance.addChip({ tag: 'tag text', });

I wish there was a simple solution like:

instance.addChip({ tag: 'tag text', color: 'teal', text-color: 'white-text', });

If anyone has any insights or suggestions, please let me know!

Answer №1

In the scenario I presented, a tag is being added from a form, showcasing one method of achieving this outcome. However, by following these steps, you can efficiently add chips, customize their appearance, and include unique attributes for better display control. This approach can be utilized to manage images, custom fields associated with database primary keys, and other related data.

// Obtain the chip instance
var chipInstance = M.Chips.getInstance($('.chips'));

// Add a new chip with relevant details such as tags and colors
chipInstance.addChip({
    tag: 'text',
    textColor: 'white-text',
    tagColor: 'red',
    tagId: id,
});

// Retrieve the chip data
var dataArray = chipInstance.chipsData;
// Access the recently added data
var myData = dataArray[dataArray.length - 1];

// Fetch all chip elements
var allChips = $(chipInstance.$chips);
// Select the most recent chip that was added
var myChip = allChips.last()[0];  // The data is located at position 0

$(myChip).addClass(myData["tagColor"]); // Apply 'red' class
$(myChip).addClass(myData["textColor"]); // Apply 'white-text' class

// It is crucial to retain this information as it serves as the database key necessary for deletion operations.
$(myChip).attr('data-id', myData["tagId"]); 
$(myChip).attr('title', 'more title text'); // Adjust attributes as needed

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

Handling an Express server that receives a request with no data

I'm struggling with a problem where I am unable to retrieve a basic JSON object. When I log it to the console, all I see is {}. Let me showcase the server code below: const express = require("express"); const app = express(); app.listen(3000); app.us ...

Encountering an "Error: Invalid string length" while attempting to iterate over the JavaScript object

I am brand new to the world of programming and currently working on developing my very first app. It's a daily expenses tracker that I have been struggling with. The issue I am facing is when a user adds a new item (such as coffee) and an amount, a ne ...

Exploring the crossroads of MongoDB, Mongoose, and Node.js: An in-depth look

Searching for ways to retrieve references in MongoDB using Node.js and Mongoose. After reading the documentation, I discovered that there are two options available: Manual References or DBRefs. Given that Manual References are recommended, I proceeded to ...

When is the appropriate time to nest CSS class selectors within other class selector definitions?

REVISED 1 After receiving feedback, I made the following changes: .lower-container { justify-content: center; position: absolute; width: 92vw; // height: 46vh; <--- no set height /* nested classes for adjusting position and height of low ...

What is the best way to integrate external JavaScript libraries into Meteor.js?

When working with Meteor, how can I incorporate a 3rd party JavaScript library like gridster.js (http://gridster.net/)? Typically, I would include the script directly in the HTML page. However, is there a way to require it directly in the JavaScript file, ...

Sequelize.js keeps the previous value for linked tables

My objective is to update the product status within the Product table. Each product has a statusId, which is either "1" or "2". The default value for statusId is always set to "1" for all products and should switch to "2" when the route is accessed once (a ...

Tips for dynamically coloring table cells in Spotfire based on their values

Creating Dynamic Table with HTML After successfully creating a cross table in Spotfire, I now aim to replicate the same table in HTML within a text area. I managed to add values using calculated values, but I'm stuck on how to dynamically set the bac ...

Grab the table headings from an HTML table and store them in variables after accessing the DOM

Looking to modify the structure of the DOM. Wanting to display table content using paragraphs instead. To achieve this, I need to extract data from each row in the table. How can I accomplish this task? <table style="width:300px"> <tr> ...

Mastering the Art of Concise Writing: Tips to

Is there a way to write more concisely, maybe even in a single line? this.xxx = smt.filter(item => item.Id === this.smtStatus.ONE); this.yyy = smt.filter(item => item.Id === this.smtStatus.TWO); this.zzz = smt.filter(item => item.Id == ...

"Trouble with Heroku: JavaScript script failing to load with 404

My adventure in building my first web app using MEAN on Heroku has been both thrilling and frustrating. I meticulously followed their guide to set up a sample app, downloaded the code, and made modifications to have a customized login page. However, I hit ...

What is the best way to implement this design using CSS flexbox?

I'm working on designing a simple layout that looks like this: https://i.stack.imgur.com/oCzyV.png Currently, I have the following HTML structure with some variations in class names and additional markup within each element: <div class="site ...

Change the background image when hovering over an element with vanilla JavaScript by utilizing data attributes

I would like to be able to change the background image of a <div> when hovering over a link. Initially, the <div> should not have a background image when the page loads for the first time. This is my current setup: <div class="background"& ...

Attempting to send a filled array to res.render, but struggling to implement a suitable async callback mechanism

I am facing a challenge in creating a function that retrieves a list of IPs from a database, collects server information based on those IPs, stores the data in objects, and finally adds these objects to an array. While I can successfully populate each obje ...

How can I activate a function or pass a selected value to a different scope variable using AngularUI Bootstrap Datepicker?

Check out this AngularUI Datepicker demo on Plunker: http://plnkr.co/edit/DWqgfTvM5QaO5Hs5dHco?p=preview I'm curious about how to store the selected value in a variable or trigger another function when a date is chosen in the field. I couldn't ...

Breaking down arrays using the JADE Template Engine

Currently, I am utilizing the JADE template engine in conjunction with ExpressJS. I am attempting to pass an array to my JADE template like so: var data = { "labels" : ["Label 1", "Label 2"] }; res.render('index', {data: data}); The struct ...

Access data from JSON array in Angular 2

I'm facing a basic issue here. I have a JSON file named pageDefinition.json that is being loaded into my component. Here's how the JSON data looks: ... "testArray": [ {"id": 0, "name": "row1"}, {"id": 1, "name": "row2"}, {"id": 2, "n ...

Implementing Icons in Custom Headers of AG Grid Using vue js

I am working on implementing a new feature in AG Grid where I want to display an info icon in the header along with a tooltip that appears when the icon is hovered over. I have already created a custom tooltip component that works correctly, but once I a ...

What steps should I take to address a problem involving a callback function?

I'm currently working on an application that aims to connect users with friends based on specific questions they answer. However, I keep encountering an error message stating "TypeError [ERR_INVALID_CALLBACK]: Callback must be a function" when the cod ...

"Exploring the power of Vue.js through dynamic and recursive components

I am struggling with creating a recursive custom component that calls itself. Unfortunately, I keep encountering an error. An unknown custom element: <TestRec> - have you registered the component correctly? For recursive components, ensure to specif ...

Datatables.js columns mismatch issue

Currently, I am facing an issue while trying to implement a datatables functionality using datatables.js in my asp.net core NET 7.0 project. The error message that keeps popping up states that there is an incorrect number of columns in the table. I have se ...