我有一个文本区域,我为用户键入了250个字符的限制。这很好用。我添加了一些代码来动态编辑该框。是否可以构造“编辑”代码来限制框,所以只有250个字符与初始添加框相同?
下面是添加框:
JSP :
<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 );
}
}
现在我得到了:
'value.length'为null或不是对象
答案 0 :(得分:1)
...
element.maxLength="250";
//add this
element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounter(undefined, 250, element);};
//end add
cell.appendChild(element);
...