yairEO/tagify

Allow max length on mix mode

ricardojbertolin opened this issue · 5 comments

It would be great if the input supports a max length attribute.

I know it would be difficult, because the length to compute should be the one from tags + input text.

But I'm missing this feature because is very usual to limit the input's max length.

What exactly do you want to happen?
Stop allowing the input of new characters once the max limit has been met?

Here's what you can do to trim the number of characters
(Make sure you are using at least Tagify version 2.22.0)

const maxChars = 200; // define the maximum allowed characters at this scope
const tagify = new Tagify(...)

tagify.on('input', function(e){
    if( e.detail.length > maxChars )
		trimValue()
})

tagify.on('add', function(e){
    // remove last added tag if the total length exceeds
    if( tagify.DOM.input.textContent > maxChars )
    	tagify.removeTag(); // removes the last added tag
})

function trimValue(){
	// reset the value completely before making changes
	tagify.value.length = 0; 
		
 	// trim the value
	let newValue = tagify.DOM.originalInput.value.slice(0, maxChars - e.detail.length);
        
	// parse the new mixed value after trimming any excess characters
	tagify.parseMixTags(newValue)
}

Yes, I would expect something similar to this, that is the natural maxlength behaviour: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_input_maxlength

Thank you for your suggestion, I will try out and come back to you.

The proposed solution didn't work as I need. However, I've developed a solution that works for me, maybe you find it useful. It's in typescript, hope you don't mind:

const tagify = new Tagify(...);
const maxLength = 200;
const nodeId = 'myComponent'; //set here the id of your HTML element

tagify.limitMaxLength = (function({ id, maxLength }) {
        const allowedKeys = ['Backspace', 'Delete', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];
        // search for the input inside tagify
        const input: HTMLElement = document.getElementById(id).getElementsByClassName('tagify__input')[0] as HTMLElement;
        // onkeydown, verify if its textContent length exceeds maximum allowed
        input.onkeydown = event => {
            if (!allowedKeys.includes(event.key) && input.textContent.length > maxLength) {
                event.preventDefault();
            }
        };

    })({ id: nodeId, maxLength });

As you can see, its a IIFE. Probably you want to adapt for your repository somehow. Hope its useful

I do not want to incorporate any of this within Tagify, because I won't know what could be the intention of the developer wanting to limit with max-chars.

Such solution should remain outside of Tagify, but be documented in the README.

Also, why did my solution didn't work for you?