纯JS字符计数器 - 为什么我的代码忽略最大值设置



不久前我整理了一个纯JS代码片段,以计算<textarea>中留下的可用字符。(非常感谢SE在那里提供的帮助。(我现在需要类似的东西,但要进行输入,因此我将稍微调整我的代码。除了我的maxlength变量外,一切似乎都很好,老实说我不知道为什么。

我使用下面的代码设置了最大长度,但似乎正在忽略 它完全。

// input attributes... 
document.getElementsByName('ptitle')[0].placeholder = 'Your Title Here...'; 
document.getElementsByName('ptitle')[0].maxLength = '28';

如果有人可以公开指出我的新秀错误,我会很感激。包括JS小提琴。


编辑:通过@Sanchit Patiyal的建议添加了SetAttribute。请参阅更新的小提琴。

您需要使用setAttribute为此

document.getElementById('text_input').setAttribute('maxlength',5);
<input type="text" id="text_input"/>

最新更新