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.
Asked
Active
Viewed 1,693 times
-4
-
http://stackoverflow.com/questions/16949716/limit-html-text-input-to-a-particular-number-of-bytes – Nope Dec 21 '16 at 09:39
-
[if you meant textarea in javascript](http://stackoverflow.com/questions/5533053/textarea-character-limit) – Kevin Kloet Dec 21 '16 at 09:39
-
1Possible duplicate of [limit text with jquery](http://stackoverflow.com/questions/13449994/limit-text-with-jquery) – Timothy Truckle Dec 21 '16 at 09:46
1 Answers
1
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">

Yosvel Quintero
- 18,669
- 5
- 37
- 46
-
So that means, if i simply limit text field size to 500, will it be equivalent to limiting to 500 bytes? – Aakash Patel Dec 21 '16 at 10:00
-
Yes, the total bytes of the text in the input.. Now you can implement your logic to notify the end user – Yosvel Quintero Dec 21 '16 at 10:03
-
1Also, what if i want to warn user on reaching max character limit? – Aakash Patel Dec 21 '16 at 10:06