Search code examples
javascriptjqueryhtmlcssmaterialize

Materialize CSS on chip delete


I have been trying to get the tag of a deleted chip from the div in the Materialize chips class, but nothing is working.

Here is what I have already tried.

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

None of the above is working.

With just only console.log(chip), I get undefined error in JavaScript console, but the function is firing when I delete the chip. I am just not able to get the value of tag of deleted chip. I want to store the tag in a variable.

I am creating chips dynamically on Materialize date select:

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

    if (chipvalue !== "") {

        // checking if tag already exits
        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 is the fiddle: https://jsfiddle.net/hq22mne4/1/


Solution

  • chips.js, which is part of materialize, doesn't seem to expose any methods for adding or removing chips programmatically. It seems to exclusively listen for an enter keydown event and then internally add the chip.

    So, I stitched together a workaround that does just that. I set potential chip's value within your onchange event:

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

    And create the chip when date picker is closed:

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

    It may not be ideal, but you should be able to tailor this going forward.

    https://jsfiddle.net/j3ej8240/