如何在h:inputTextarea上设置maxlength属性 [英] How to set maxlength attribute on h:inputTextarea

查看:248
本文介绍了如何在h:inputTextarea上设置maxlength属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何限制<h:inputTextarea>的长度?对于<h:inputText>,它可以与maxlength属性一起正常工作.但是,该属性在<h:inputTextarea>中不可用.

How can I limit the length of <h:inputTextarea>? For <h:inputText> it works fine with maxlength attribute. However, this attribute is unavailable in <h:inputTextarea>.

推荐答案

HTML5 + JSF 2.2 +

如果您使用的是HTML5和JSF 2.2+,请将其指定为

HTML5 + JSF 2.0/2.1

如果您使用的是HTML5,但尚未使用JSF 2.2,请使用 OmniFaces

HTML5 + JSF 2.0/2.1

If you're using HTML5, but not JSF 2.2 yet, use OmniFaces Html5RenderKit to recognize new HTML5 attributes in JSF 2.0/2.1.

<h:inputTextarea value="#{bean.text}" maxlength="2000" />

HTML4

如果您使用的是HTML4,那么HTML本身已不支持它.它仅在<input>元素上受支持,而在<textarea>元素上不受支持.这就是为什么此HTML元素的JSF表示形式上没有这样的属性的原因.您需要使用JS在客户端和/或使用JSF在服务器端解决此要求. JS使您可以立即验证长度,而忽略所有其他字符.通过JSF,您还可以在客户端禁用或入侵JS代码的情况下对其进行验证.最好将两者结合起来.

HTML4

If you're on HTML4, then it's already not supported by HTML itself. It's only supported on <input> element, not on <textarea> element. That's also why there's no such attribute on the JSF representation of this HTML element. You need to solve this requirement at the client side using JS and/or at the server side using JSF. JS enables you to instantly validate the length and ignore all other characters. JSF enables you to validate it as well for the case that the client disabled or hacked the JS code. Best would be a combination of both.

假设您有一个

<h:inputTextarea value="#{bean.text}" styleClass="max">
    <f:validateLength maximum="2000" />
</h:inputTextarea>

这是您可以使用jQuery

here's how you could do the jQuery

$('textarea.max').keyup(function() {
    var $textarea = $(this);
    var max = 2000;
    if ($textarea.val().length > max) {
        $textarea.val($textarea.val().substr(0, max));
    }
});

这篇关于如何在h:inputTextarea上设置maxlength属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆