我一直在尝试使用javascript通过按钮添加到textarea的maxlength。它目前的作用是计算您可以输入的剩余字符数。我希望它还有一个可以添加20的按钮。但是,该按钮不会向maxlength添加20。这是我的代码:
使用Javascript:
var el_t = document.getElementById('textarea');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length - this.value.length);
};
function addLength() {
document.getElementById('count').innerHTML = (document.getElementById('textarea').maxlength + 20);
}
HTML:
<textarea id="textarea" maxlength="99" placeholder="Type..."></textarea>
<span id="count"></span>
<button onclick="addLength()">Add to character limit!</button>
答案 0 :(得分:0)
maxLength属性应该有一个大写字母L,而你的属性有一个小写字母l。这是一个例子:
HTML
<textarea col='30' rows='4' maxlength='50' id='t1'></textarea>
<button onclick='maxchange()'>SUBMIT</button><br>
<div id='d1'></div>
的Javascript
function maxchange() {
document.getElementById('t1').maxLength +=5;
document.getElementById('d1').innerHTML=document.getElementById('t1').maxLength;
}
答案 1 :(得分:0)
你很亲密。处理重新计票
<强>的Javascript 强>
var el_t = document.getElementById('textarea');
var length = function(){ return el_t.getAttribute("maxlength");};
var el_c = document.getElementById('count');
el_c.innerHTML = length();
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length() - this.value.length);
};
function addLength() {
var count = parseInt(length()) + 20;
document.getElementById('count').innerHTML = count;
el_t.setAttribute("maxlength",count);
triggerEvent(el_t,"keyup");
}
function triggerEvent(el, type){
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
<强> HTML 强>
<textarea id="textarea" maxlength="99" placeholder="Type..."></textarea>
<span id="count"></span>
<button onclick="addLength()">Add to character limit!</button>