the text input only allows three words separated by spaces, and if it exceeds 3, the user can\'t input anymore, is this possible using jQuery? I can use keyup event to liste
EDIT: Something like this should do it (tested):
$('#myTextbox').keyup(function(e){
var wordArr = $(this).val().split(' ');
if(wordArr.length > 3 && e.keyCode == 32) {
var arrSlice = wordArr.slice(0,3);
var newStr = arrSlice.join(' ');
$(this).val(newStr);
}
});
If the user attempts to type in more than three words, the contents will be overwritten with only the first three words. This solution will show characters being removed as they are typed if three words are exceeded, thus providing a bit of feedback.
If that's not the desired behaviour, @Jataro's solution is the way to go.
May be something like,
$('#myTextbox').change(
function()
{
var input = $(this).val();
var numberOfWords = input.split(' ').length;
if(numberOfWords > 3)
{
$(this).val(input.substring(0, input.lastIndexOf(' ')-1));
}
}
);
I haven't verified this code, but something like this should work.
And yes, as mgroves said, don't forget to re-validate everything on the server.
Check if the input already has 3 words and they are trying to enter a space. If so return false:
$('#myTextbox').keydown(
function(event)
{
var input = $(this).val();
var numberOfWords = input.split(' ').length;
if(numberOfWords == 3 && event.keyCode == 32)
{
return false;
}
}
);
Edit: There was an additional question about the situation where someone might past text in the field. As a cross browser solution I would probably bind code similar to @karim79's to the blur event.
$('#myTextbox').blur(
function(e)
{
var tokens = $(this).val().split(' ');
if(tokens.length > 3)
{
$(this).val(tokens.slice(0,3).join(' '));
}
}
);