Reputation: 582
I don't know what I'm doing wrong but basically this is what I have.
JQuery:
$(document).ready(function(){
$('form#status_form').submit(function(){
var statusV = $('input#status_updated2').val();
if(statusV.length > 255)
{
$('em#statusError').fadeIn().fadeOut(5000);
}
else
{
//do cool stuff
}
});
});
The HTML form that it's pulling from:
<em style="display:none;"id="statusError">*NO MORE THAN 255 CHARACTERS</em>
<form id="status_form" name="status_form">
<input type="text" id="status_updated2" size="57" />
</form>
If I enter way more that 255 characters the error message won't come up like it should and the fnctions in the "else" statement go through. What am I missing?
Upvotes: 0
Views: 318
Reputation: 3002
The logic is fine. But you might forget to call e.preventDefault() to prevent the #status_form from submitting, which breaks the statusError message.
$('form#status_form').submit(function(e){
...
$('em#statusError').fadeIn().fadeOut(5000);
e.preventDefault();
Upvotes: 1
Reputation: 4049
You most likely need to capture the default form submit event. Try:
$('form#status_form').submit(function(evt){
evt.preventDefault();
...
}
Upvotes: 1
Reputation:
The reason you're not seeing the message is that you're not preventing the default action (form submission) from occurring if there's an error. You can stop this like so:
$(document).ready(function(){
$('form#status_form').submit(function(event){
var statusV = $('input#status_updated2').val();
if(statusV.length > 255)
{
event.preventDefault(); // stop the form submitting if there's an error.
$('em#statusError').fadeIn().fadeOut(5000);
}
else
{
//do cool stuff
}
});
});
See the jsfiddle here for a working example.
Upvotes: 1
Reputation: 76003
How about binding to the keydown
event and return
ing false
if there are already too many characters:
$('input[type="text"]').on('keydown', function (event) {
//check if the character limit has already been reached, but always allow backspace key strokes and delete key strokes
if (this.value.length >= 255 && event.which != 8 && event.which != 46) {
//this will stop the current key stroke from being added to the value of the input
return false;
}
});
Here is a demo: http://jsfiddle.net/5yRK2/
event.which != 8 && event.which != 46
--> this allows the backspace and delete keys to do their thing (since they remove characters instead of add them).
Upvotes: 1