javascriptjavajquerybytecharacter-limit

How can i set text field limit to 500 bytes?


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.


Solution

  • 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">