Search code examples
javascriptphphtmlspecial-characterslimit

Need to limit the comma(,) entered in textbox


I need to place a limit for the number of commas entered in the text area

I tried these links but it dint help

Limit the number of commas in a TextBox

The comma in the textBox

Iam using php. Is it possible to implement php or javascript here.


Solution

  • You should wait for DOMContentLoaded event, and afterwards bind the textarea with a callback for the "input" event:

    const MAX_COMMAS = 3;
    document.addEventListener("DOMContentLoaded", function(event) {
        let textarea = document.getElementById('textbox');
    
        textarea.addEventListener("input", function(event) {
            let matchCommas = this.value.match(/,/g);
    
            if (Array.isArray(matchCommas) && matchCommas.length > MAX_COMMAS) {
                this.value = this.value.substring(0, this.value.length - 1); // remove the last comma
                alert("MAX COMMAS EXCEEDED!");
            }
        });
    });
    <textarea id="textbox" cols="40" rows="4"></textarea>