I’m trying to make a simple character counter which shows whether the user has typed in the minimum number of characters before they can press enter.
$(document).ready(function(){
$('#notification').hide();
$('#press_enter_notification').hide();
var allow_enter = false;
var min = 4;
var max = 30;
var char_count = 0;
$("#form_textbox").keydown(function() {
$('#press_enter_notification').hide();
if(this.value.length < min) {
char_count = min - (this.value.length) -1;
//alert('Too short');
$('#notification').show("fast");
$('#notification').text(char_count + ' more characters to go');
allow_enter = false;
} else if(this.value.length >= max) {
char_count = (this.value.length) - max;
this.value = this.value.substring(0,max);
$('#notification').show("fast");
$('#notification').text(' no more characters remaining');
} else {
char_count = max - (this.value.length) -1;
$('#notification').show("fast");
$('#notification').text(char_count + ' characters remaining');
$('#press_enter_notification').show("fast");
allow_enter = true;
}
});
$("form").submit( function () {
if (allow_enter == false)
{
$('#press_enter_notification').show("fast").text('you cannot press enter yet');
return allow_enter;
}
} );
});
It works, however it has the following quirks:
- When you type something in and delete all the text, the character count message doesnt dissapear, or count backwards
- When you delete everything it says 3 more characters to go, I had to add -1 at
if(this.value.length < min) {, otherwise it lets you enter 5 characters before it stops saying 3,2,1 more characters to go.
char_count = min - (this.value.length) -1;
If you try this out in a browser or jsbin you will notice them. How can I structure this to sort it?
Thank you.
You need to change
keydown()tokeyup()as the length isn’t registered until the key press is fully complete. The only thing you need to check for keydown with is if you’re preventing the default on things like return or tab.You can also remove the -1 hack now.
JS Fiddle: http://jsfiddle.net/VPD3j/