Implementing Materialize CSS functionality for deleting chips

I've been attempting to extract the tag of a deleted chip from the div within the Materialize chips class, but I'm hitting roadblocks.

My failed attempts so far:

$('.chips').on('chip.delete', function(e, chip){
    console.log(chip);
    console.log(e);
    console.log(chip.tag);
});

None of the above code is yielding results.

Even when I simply use console.log(chip), I encounter an undefined error in the JavaScript console. The function does trigger upon deleting the chip, however, I cannot access the value of the tag of the deleted chip. My aim is to store this tag value in a variable.

I am dynamically creating chips based on Materialize date selection:

$('#pm_date').change(function () {
    var chipvalue = $(this).val();

    if (chipvalue !== "") {

        // verifying if the tag already exists
        if ($("#date_chip_select:contains(" + chipvalue + ")").length > 0) {
            alert('Date already selected');
        } else {
            var appendstring = "<div class='chip' id='date_chip_child_" + chip_id + "'>" + chipvalue + "<i class='material-icons close'>close</i></div>";
        }
    }
});

Here's the fiddle link for further reference: https://jsfiddle.net/hq22mne4/1/

Answer №1

chips.js, a component of the materialize framework, does not provide any built-in methods for programmatically adding or removing chips. Instead, it seems to only listen for an enter keydown event and internally handle chip creation.

To work around this limitation, I devised a solution where I set the value of a potential chip within the onchange event:

$("#datechips").find('input').val($(this).val());

I then create the chip when the date picker is closed:

$('.datepicker').pickadate({
    selectMonths: true,
    selectYears: 15,
    onClose: function() {
        // add chip by populating the input and simulating enter key press
        $("#datechips").find('input').trigger({ type : 'keydown', which : 13 });
},
});

While not an ideal workaround, you can customize this approach as needed in the future.

https://jsfiddle.net/j3ej8240/

Answer №2

I've been tackling this issue with capturing add and delete chip events without relying on jQuery, and here's how I managed to do it:

function chipDeleted(e, data) {
    console.log("Chip was deleted with text: " + data.childNodes[0].textContent);
}

function chipAdded(e, data) {
    console.log("Chip was added with text: " + data.childNodes[0].textContent);
}


//
document.addEventListener("DOMContentLoaded", function (e) {
    console.log("DOM fully loaded and parsed");
    var firstTag = "Initial Tag";
    var elems = document.querySelectorAll('.chips');
    var instances = M.Chips.init(elems, {
        data:[{
              tag: firstTag
          }],
        autocompleteOptions: {

            limit: Infinity,
            minLength: 1
        },
        placeholder: "No search...",
        onChipDelete: function (e, data) { chipDeleted(e, data) },
        onChipAdd: function (e, data) { chipAdded(e, data) }
    });
});

This is what my HTML section looks like:

<body>
    <div class="chips search-history"></div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>

</body>

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

Add unique content to a div upon page reload

Whenever the page is refreshed, I would like to add a random anchor from an array into a specific div. Here's my current code: <div id="exit-offer" class="exit-offer-dialog"> <div class="offer-content" id="banner-load"> <bu ...

Implementing Jquery to Repurpose a Function Numerous Times Using a Single Dynamic Value

Important: I have provided a functional example of the page on my website, currently only functioning for the DayZ section. Check it out here Update: Below is the HTML code for the redditHeader click event <div class="redditHeader grey3"> & ...

Can the autoscroll offset be adjusted while dragging?

I am developing a single-page application using Vue.js. The user interface consists of three main components: A fixed navbar at the top with a z-index of 2 A fixed sidebar on the left with a z-index of 1, and padding to accommodate the navbar A central ar ...

Having trouble getting jQuery click event to work with Express for loading a Handlebars page

My jQuery on click function is not working properly in conjunction with Express to route to a handlebars page and display the passed information. I have attempted different solutions such as changing the HTTP method from GET to POST, not using handlebars ...

Interactive KML layer in ArcGIS mapping tool

Currently, I am working on enhancing an ArcGIS map by incorporating KML layers for interactivity. This is a simplified version of the code I am currently using: map = new Map("map", { basemap: "topo", center: [-108.663, 42.68], zoom: 6 }); parser.p ...

Style the "focus" pseudo-class of an input element using Vue programmatically

Currently, I have been utilizing event listeners to manipulate the :focus pseudo-class of an input element: const element = document.getElementById("myElementID"); element.addEventListener("focus", (e) => { e.target.style.borderCo ...

JavaScript: Struggles with utilizing a function as an argument and later executing it inside a nested function

I've been struggling with defining a new function, and I need help resolving it. Here's an example that I was initially referencing: Pass arguments into ajax onreadystatechange callback? I wasn't able to find the solution through research, ...

Challenge in Decision Making

I am curious why this type of selection is not functioning properly for html select options, while it works seamlessly for other input types like Radios or checkboxes. Any thoughts? $('#resetlist').click(function() { $('input:select[nam ...

Custom Email Template for Inviting Msgraph Users

I'm currently exploring the possibility of creating an email template for the MS Graph API. I am inviting users to join my Azure platform, but the default email they receive is not very visually appealing. public async sendUserInvite(body: {email: < ...

Tips on incorporating the wait function within the evaluation_now action in Nightmare?

While I am incorporating Nightmare actions in my script, a question arises regarding the use of the wait function within the evaluate_now function. How can I utilize the wait function within the evaluate_now function? I am aware that I can simply use the ...

The website was designed to only allow scrolling on desktop devices, not on mobile devices

I noticed that the website is not scrolling properly on mobile devices, specifically when viewed on a Samsung Galaxy S4 Mini. Does anyone have suggestions on how to resolve this issue? ...

Loading a unique shape using JSON within the KineticJS framework

Is there a way to load a unique custom shape using a Json file in Kinetic JS? The documentation I found only covers loading normal shapes. ...

Obtaining the NodeValue from an input of type <td>

I have a HTML code snippet that I am trying to parse in order to extract the nodeValue of all elements within the table columns. <table id="custinfo"> <tr> <td><label>First Name</label></td> <td& ...

Introducing Block Insert feature in React Draft-js - a powerful

How the Process Works: Upon hitting the spacebar, the Draft-JS editor queries the text content for a specific word. Subsequently, all instances of that word are enveloped in tags. The HTML is then converted back and the state of the Draft-JS editor is upd ...

Python HTMLParser: Extracting HTML tag content made easy!

After working through an HTML page, I have now reached a point where I have lines that look like this: <td class="border">AAA</td><td class="border">BBB</td> I am trying to extract AAA and BBB into variables using HTMLParser, but ...

When utilizing the File System Access API, the createWritable() method functions perfectly within the console environment but encounters issues when executed

I've been diving into the File System Access API for an upcoming project and I'm struggling with using the createWritable() method. Specifically, I'm encountering issues with this line of code: const writable = await fileHandle.createWritab ...

Removing CSS from an HTML document using Gulp

My Web App is built using Angular and I encountered an issue with Gulp. Every time I add a new custom CSS line to my HTML file and run Gulp, it automatically removes that line from the file. <!--MATERILIZE CORE CSS--> <link h ...

What is the syntax for creating a link tag with interpolation in Angular 2 / Ionic 2?

As I work on developing an app using Ionic 2/Angular 2, I have encountered a challenge that I am struggling to overcome. Let me provide some context: I am retrieving multiple strings from a webservice, and some of these strings contain links. Here is an e ...

Ways to enhance the Response in Opine (Deno framework)

Here is my question: Is there a way to extend the response in Opine (Deno framework) in order to create custom responses? For instance, I would like to have the ability to use: res.success(message) Instead of having to set HTTP codes manually each time ...

Use Javascript to display or conceal events on a fullcalendar interface

I am in the process of creating a religious calendar as part of a project that displays various events from major religions. Using the full calendar, I have included a "religion key" at the top of the calendar to differentiate between different faiths. My ...