Javascript文本区域限制问题

javascript textarea restriction problem

本文关键字:问题 区域 文本 Javascript      更新时间:2023-09-26

我有一个文本区域,我为用户输入设置了250个字符的限制。这很好。我添加了一些代码来动态编辑这个框。是否有可能构建"编辑"代码来限制框,所以只有250个字符,就像最初的添加框一样?

添加框:

<<p> jsp/strong>:
<td colspan="3">
    You have <strong><span id="commentsCounter">${const['COMMENT_MAX_LENGTH']}</span></strong> characters left.<br/>
    <textarea id="comment" name="comment" rows="3"
        onfocus="characterCounter('commentsCounter',${const['COMMENT_MAX_LENGTH']}, this)"
        onkeydown="characterCounter('commentsCounter',${const['COMMENT_MAX_LENGTH']}, this)"
        onkeyup="characterCounter('commentsCounter',${const['COMMENT_MAX_LENGTH']}, this)"></textarea>
        <a href="javascript:addComment();"><img src="../images/icon_add.gif" border="0" alt="Add"/></a>
</td>
javascript

:

    function characterCounter(id, maxLen, inputElement)
{
    spanId = document.getElementById(id);
    if (spanId)
    {
        // Update the counter the user sees.
        var whatIsLeft = maxLen - inputElement.value.length;
        if ( whatIsLeft < 0 ) whatIsLeft = 0;
        spanId.innerText = whatIsLeft;
    }
    // Restrict user from entering more than the maxlen.
    if ( inputElement.value.length > maxLen )
    {
        inputElement.value = inputElement.value.substring( 0, maxLen );
    }
}

下面是编辑该框....的代码片段我如何在下面构造镜像上面的javascript只是为了阻止输入超过250个字符的框?

    function editCommentToggle( id )
{
    theRow = document.getElementById("id"+id);
    //user = theRow.cells[0].innerHTML;
    //date = theRow.cells[1].innerHTML;
    com = theRow.cells[2].innerHTML;

    idx = 2;

        // Comment field
        cell = theRow.cells[idx];
        while( cell.childNodes.length > 0 ) cell.removeChild(cell.childNodes[0]);
        element = document.createElement("textarea");
        element.id="comments-"+id;
        element.rows="3";
        element.value = com;
        element.style.width =  "400px";
        element.maxLength="250";
        cell.appendChild(element);

只是补充道:

maxlength = 250;
element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit(undefined, maxlength, element);}; 
        cell.appendChild(element);
 function characterCounterEdit(id, maxLen, inputElement)
{
    spanId = document.getElementById(id);
    if (spanId)
    {
        // Update the counter the user sees.
        var whatIsLeft = maxLen - inputElement.value.length;
        if ( whatIsLeft < 0 ) whatIsLeft = 0;
        spanId.innerText = whatIsLeft;
    }
    // Restrict user from entering more than the maxlen.
    if ( inputElement.value.length > maxLen )
    {
        inputElement.value = inputElement.value.substring( 0, maxLen );
    }
}

现在我得到:

的值。

...
element.maxLength="250";
//add this
element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounter(undefined, 250, element);};
//end add
cell.appendChild(element);
...