Search code examples
javascriptdompreventdefault

Can't input text after deleting it


I made an input text that once it reaches 10 characters it will turn red. I cannot add text if i delete some of the input text that is already there. It's a must that i have to do it with preventDefault.

1) How can i make my code work and let me input after i deleted some of the text. 2) Is there a way to do it without using addEventListener but still using preventDefault? I'm rather new to this javaScript stuff. Thank you in advance.

function ceScriu() {

  var numeInput = document.querySelector("[name='nume']");
  var nume = numeInput.value;
  var nu = nume.toString().toLowerCase();
  var divInput = document.querySelector("[name='divul']");
  var div = nu.length;

  document.querySelector("[name='divul']").innerHTML = div;

  if (div > 9) {
    numeInput.addEventListener("keypress", function(event) {
      event.preventDefault()
    });
    divInput.classList.add("counter");
  } else {
    divInput.classList.remove("counter");
  }
}

the code is working fine. The counter turns red when it reaches 10. But if i write characters, delete them and then try again to write some more, i cannot input any characters.


Solution

  • EDIT: Please check this pluker https://plnkr.co/edit/ny35WPX3fsTmw1oWY1j8

    I modified your code to check for length inside the event listener as follows

    window.onload = function () { 
      var numeInput = document.querySelector("[name=nume]");
      numeInput.addEventListener("keypress",function(event){
                  var nume = numeInput.value;
                  var nu = nume.toString().toLowerCase();    
                   var divInput = document.querySelector("[name=divul]");
                   var div = nu.length;
                   document.querySelector("[name=divul]").innerHTML = div;
                   if(div > 9){
                     event.preventDefault();
                     divInput.classList.add("counter");        
                   }else{    
                     divInput.classList.remove("counter");
                   }
      });
    
    }