i am using a function that limit textArea length. Although function is performing well but i want to ask whether i am calling function in right way?
Here it is
<h:inputTextarea id="questionInputTextArea"
value="#{faqAddUpdate.question}"
cols="50"
rows="3"
disabled="#{faqAddUpdate.buttonState}"
onkeypress="limitTextArea(this, 400)"
style="overflow: auto;">
<f:validateLength maximum="200" />
</h:inputTextarea>
Here is the function
function limitTextArea(element, limit) {
var $textArea = $(element); //casting to jQuery so we can use jQuery functions on it
($textArea).keypress(function(event){
if (event.which < 0x20) {
// e.which < 0x20, then it's not a printable character
// e.which === 0 - Not a character
return; // Do nothing
}
if ($textArea.val().length == limit) {
event.preventDefault();
} else if ($textArea.val().length > limit) {
// Maximum exceeded
$textArea.val() = $textArea.val().substr(0, limit);
}
}); //end of keypress
} //end of function()
The thing that confusing me is this, i am using onkeypress in my jsf code, and in the function i am also saying that ($textArea).keypress(function(event). How can i optimize this function? Or i am doing right?
Thanks
You’re attaching a new keypress event listener everytime a key is pressed. This makes no sense. You need to either specify it straight in
onkeypressattribute, or to attach it by jQuery means after document ready. Further the assignment toval()function makes no sense, you’d need to pass the new value as its argument instead. This can impossibly be “performing well”. Finally, I’d also suggest to usekeyupinstead ofkeypressso that the function is only invoked after the value of the textarea is been updated which results in a more sane behaviour of the limit function. This way you also don’t need to check for non-printable character ranges.All with all, it can just look like this:
which is to be registered as
If you really need to attach it by jQuery
keyup()function, then you’d have to specify the limit in the function yourself.E.g.
with
(which you execute during
$(document).ready(function() {...})or$(function() {...});)Or you could specify the limit as part of class name and extract it accordingly:
with something like this
By the way, the limit of
400doesn’t match the limit which you’ve there in the server side<f:validateLength>validator.