simplemde-markdown-editor
simplemde-markdown-editor copied to clipboard
Textarea Character Limit
Is there anyway to limit the character on textarea ??
I also try to combine with other JS such as http://stackoverflow.com/questions/5533053/textarea-character-limit
but still didn't work. Any solution would be appreciated.
Thanks brother
I'd love this as a configuration option as well, especially since maxlength="50"
doesnt work on <textarea>
anymore with this simple-mde.
My solution so far is the following, just disabling the submit-button when the limit is reached:
<script>
char_limit = 50;
var simplemde = new SimpleMDE({
status: [ {
className: "chars",
defaultValue: function(el) {
el.innerHTML = "0 / "+char_limit;
},
onUpdate: function(el) {
el.innerHTML = simplemde.value().length + " / "+char_limit;
limit_characters()
}
}]
});
function limit_characters() {
character_count = simplemde.value().length
if (character_count > char_limit) {
$('#submitBtn').attr("disabled", true);
} else {
$('#submitBtn').attr("disabled", false);
}
}
</script>
Don't forget to add id="submitBtn" to the button element and disable it by default.
Not the best solution I know, but the only one I came up with.
Updating @lupas code for lines as well, if anyone wants it
lines_limit = 15;
should give you lines count
{
className: "lines",
defaultValue: function(el) {
el.innerHTML = "Lines 0 / "+lines_limit;
},
onUpdate: function(el) {
el.innerHTML = " Lines "+ simplemde.codemirror.lineCount() + " / "+lines_limit;
limit_characters() //update this function according to lines_count = simplemde.codemirror.lineCount();
}
}]
Sorry if it is messy, I copied from my code and edited directly here
Just ran into this myself and discovered that you can listen to the codemirror
's beforeChange
event, which receives a change
argument (https://codemirror.net/doc/manual.html#events).
If you're trying to implement a max length, you can simply check the SimpleMDE instance .value().length
and call change.cancel()
if it exceeds some limit.
My solution for the @martinrue comment. It is working for me.
editor.codemirror.on('beforeChange', (instance, changes) => {
if(editor.value().length > 5000 && changes.origin !== "+delete"){
changes.cancel();
setErrorMessage($el, 'Too big'); // A visual effect for the user
}
if(editor.value().length <= 5000 && changes.origin == "+delete"){
resetErrorMessage($el);
}
});
Need to cover various corner-cases like pasting, highlight+paste, partialHighlight+paste, etc.