lundi 23 octobre 2017

If statement to make textarea have a maxLength of 0

I've been trying to make a textarea that shows how many characters you have left to type (it shows the maxLength). That works. Recently, I added buttons that can add and subtract from the textarea's maxLength. The problem is, subtracting can put the maxLength in the negatives, which makes the maxLength really infinite. Can someone give me an if statement that will set the maxLength to 0 if it is less than 0? Here's my code:

Javascript:

//How many characters the textarea has left
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);
};

//Add and subtract textarea maxlength
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);
    }
}
function subLength() {
  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 style="width:150px;" id="textarea" maxlength="50" placeholder="Type..."></textarea>
<span id="count" style="color:black"></span>
<button onclick="addLength()" style="color:black;">Add to character limit!</button>
<button onclick="subLength()" style="color:black;">Subtract from character limit!</button>

Aucun commentaire:

Enregistrer un commentaire