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

Excessive gap located above the section element

On the web page I'm practicing with, I've noticed an unwanted space at the top of the "Favorite Food" section. To center my unordered list, I made the "section" elements inline-block, but this created the issue. How can I remove that space at the ...

How can I send data in JSON format to a JavaScript AJAX request?

I've created a method that looks like this: public String getUTResult() throws IOException { BuildResultParser bp = new BuildResultParser(); BuildResultBean b = bp.getreadFile("C:\\bc.txt"); String str = b.getuTresult(); ...

Having trouble finding rows to manipulate in an HTML table generated using jQuery csvToTable?

As a beginner in programming, I find myself seeking assistance with a particular issue. I have successfully read a CSV file stored locally and transformed it into an HTML table using jQuery csvToTable http://code.google.com/p/jquerycsvtotable/. Additional ...

What is the reason that setting the margin of 0 on the body does not eliminate the margin on an h1 element?

I believe the body element should apply styles to all elements contained within it. In this scenario, I am attempting to give my h1 element a margin of 0. body { font: 15px/1.5 Arial, Helvetica, sans-serif; padding: 0; margin: 0; background ...

Employ the power of AJAX to selectively display or conceal a specific group of images

Have you ever thought about showcasing a large number of images on a non-CMS website? Say you have 50 images that can't all be displayed at once. One idea is to display the first 15, then allow users to click "Next" to reveal the next batch of 15, and ...

The allure of Beautiful Soup lies in its ability to effortlessly gather every <br/> tag nestled within the <strong> element

I'm facing a peculiar issue that's getting on my nerves. Trying to convert HTML into markdown, but the formatting of my HTML is quite unusual. It includes things like: <strong>Ihre Aufgaben:<br/></strong> and <strong> ...

Arrow function utilized in string rendered component

Hello everyone, I could use some help with the following code snippet: rowRenderer = (e) => { debugger; return e.data?.fileName ? '<a class="documentLink" onclick={() => \'' + console.log('\ ...

Strange behavior observed with CSS intellisense in Visual Code

While working on a ReactJS project, I noticed that when I opt for the style Jsx Attribute for inline CSS, . CSS intellisense seems to not work or only work after I manually add some fields. However, if I manually type the style attribute without using t ...

Transmit information via AJAX to the @RequestBody annotation in a Spring application

When working with Spring Java, I used response entity and request body to insert data but encountered an error - 404 not found. This is my controller: @RequestMapping(value = "insertuserlogin/", method = RequestMethod.POST) public ResponseEntity<?> ...

Label dynamically generated from user input for radio button option

In my attempt to develop a radio group component, I encountered an issue where the value of one radio option needs to be dynamically set by an input serving as a label. While I have successfully created similar components before without React, integrating ...

Ways to transform a 4-column CSS table into a 2-column layout for mobile and tablet viewing

For my latest project, I am faced with the challenge of creating a responsive table that transforms from 5 columns to 2 columns on smaller screens. While using complex jQuery is an option, I prefer a more semantic approach. Additionally, I need to incorpor ...

What is the best way to arrange an array in either javascript or typescript based on a specific key, and in the case of identical keys,

Below is an array with objects that need to be sorted: [ { "Books": [], "_id": "5dea9a11a8e1bf301c462ce4", "FileName": "AAAAA", "Order": 99999 }, { "_id": "5dea9864a8e1bf301c462cdb", "Books": [], "FileName": "some1", ...

Update the Material UI input field value using an external JavaScript script

Imagine I find myself exploring an online form that utilizes Material UI components, for instance, this example link. I am interested in automatically filling the input fields with a specific value using JavaScript in the console: for (input of document.g ...

Mobile webpage utilizing jQuery live click event binding

I am currently in the process of creating a mobile-friendly website that includes a list of names. I have successfully implemented a click event using jQuery for all devices, including Android, Blackberry, and Nokia. However, when testing on an iPhone, I ...

Changing the color of error messages when validating input with jQuery Validation and Bootstrap 5

Modified: I have implemented jquery-validation and bootstrap 5 to handle form validation and display error messages. Strangely, when I attempt to log in without entering an email and password, the input fields turn red (indicating an error) for both the em ...

Is there a way to use the datepicker in inline mode while also adding a year dropdown feature to it?

Is it feasible to incorporate a year/month drop-down feature into an inline date picker using JQuery Datepicker? For more information, visit: http://jqueryui.com/datepicker/ ...

Creating a wrapper function for the map method in React

When attempting to incorporate a parameter into my map function in React, I encountered an issue where the return value turned null after encapsulating it within another function. This became apparent during debugging, especially when using console.log(mar ...

Struggling to make button switch in my Spring Boot Application (e.g. from "Add to Cart" to "Remove")

My application allows users to add items to their cart, which are then persisted using Spring Data JPA and saved in a MySQL database. I am looking to change the text from "Add to Cart" to "Remove" when the button is clicked, and vice versa. I have attempt ...

Ways to manage the gap among flex items

I'm currently going through some educational material on Codeacademy, and I'm curious about how I can control the spacing between the "locations" text and the three divs below it. The task requires me to create a 15px gap between them, but I am u ...

"PxToRem: A handy PostCSS plugin for converting pixel units

As a beginner in the world of Node.js and post processors for CSS, I recently took the time to install the following tools after going through multiple articles: Node.js (including npm) Gulp PostCSS Pxtorem (a PostCSS plugin for Gulp) My goal is to util ...