Reputation: 405
I have a text box in my JSP-page which allow user to enter the name also in which I have given the max limit in 30 character.
But when user enters the empty white space it count the and does not allow character to enter once it reaches the max limit.
I want that when the white spaces is enter user should able to enter the character. It should not count white spaces.
Upvotes: 0
Views: 1452
Reputation: 802
you could just use the
$('input').keyup(function(event) {
if (event.keyCode == 32) { // if the user presses 'space',
$(this).val(function(i, val) {
return val.replace(' ', ' '); // find and replace 'double spaces' and replace it with one 'space
});
}
});
check my DEMO
this code allows for the max of ONE space next to each other incase the user wants to put a last name. just and option. if you dont want this then use the code from the other answers.
Upvotes: 0
Reputation: 4474
Or again:
$('input').keypress(function(){
var t = $(this).val();
console.log(t.replace(/\s/g, '').length);
if(t.replace(/\s/g, '').length >= 10) alert('max');
});
Upvotes: 0
Reputation: 9469
Try this:
$(function() {
var txt = $("#myTextbox");
var func = function() {
txt.val(txt.val().replace(/\s/g, ''));
}
txt.keyup(func).blur(func);
});
You have to additionally handle the blur
event because user could use context menu to paste.
Upvotes: 2
Reputation: 1241
You can replace all space with empty string and count characters.try this code :
function get(str){str = str.replace(/\./g,' ');return str.length;}
Upvotes: 0