Reputation: 1507
How can I return an error message to users when they try to go past the max length in a text area?
Is there a way for HTML to return an error to the user?
Upvotes: 2
Views: 51512
Reputation: 306
A solution for all input fields that has MAXLENGTH attribute defined, so that you don't have to apply size for each element.
$("input[maxlength], textarea[maxlength]").keyup(function () {
var max = $(this).prop('maxlength');
if ($(this).val().length > max) {
alert('value must be less than ' + max + ' characters');
}
});
Upvotes: 1
Reputation: 76
<input type="text" name="fieldname" maxlength="10">
You can use the maxlenght
attribute to forbid entering more characters than intended. You will not need JS for this.
If you still want to use JS, then:
$("#myformid").keypress(function() {
if($(this).val().length > 10) {
//display your warinig the way you chose
}
]
});
Upvotes: 6
Reputation: 51
Here's the code to validate user input without having to use Jquery.
<textarea id=txt onKeyUp=check() maxlength=10>
Abc
</textarea>
<div id=warning></div>
<script>
function check() {
stringLength = document.getElementById('txt').value.length;
if (stringLength >= 10) {
document.getElementById('warning').innerText = "Maximum characters are 10"
} else {
document.getElementById('warning').innerText = ""
}
}
</script>
Upvotes: 0
Reputation: 8101
function check_length(my_form)
{
maxLen = 50; // max number of characters allowed
if (my_form.my_text.value.length >= maxLen) {
var msg = "You have reached your maximum limit of characters allowed";
alert(msg);
my_form.my_text.value = my_form.my_text.value.substring(0, maxLen);
}
}
<textarea onKeyPress=check_length(this.form); onKeyDown=check_length(this.form); name=my_text rows=4 cols=30></textarea>
Upvotes: 0
Reputation: 7289
Sure this is possible! First, count the entered characters and then print out the message you'd like to (here: "Characters left: X", the max length is 100 in my example).
Here is the JSFiddle!
HTML:
<textarea rows="4" cols="50" id ="yourtextarea">
</textarea>
<div id="info"></div>
JS:
$("#yourtextarea").keyup(function(){
$("#info").text("Characters left: " + (100 - $(this).val().length));
});
Upvotes: 3