How can i set text field limit to 500 bytes?

1.8k views Asked by At

I have one text field and I want to limit its max enter character limit to 500 bytes. How is it possible? May be I should use jQuery for that. But I don't know how. Any best example? In my question, I want to limit character limit to 500 Bytes, which is different than 500 character.

1

There are 1 answers

3
Yosvel Quintero On BEST ANSWER

Using JavaScript's Blob.size you can get the number of bytes from a string like this:

document
  .getElementById('str')
  .addEventListener('input', (e) => {
    const bytes = new Blob([e.target.value]).size
    // your logic...

    console.clear()
    console.log(`${bytes} bytes`)      
  })
<input type="text" id="str">