简体   繁体   中英

How can I make an element appear (for instance a tick) when a certain amount of characters have been typed into an input field?

I have created a simple Javascript Validation script:

var el = document.getElementById("username");
var el_pwd = document.getElementById("password");
var el2 = document.getElementById("feedback");
var el3 = document.getElementById("ok");
var el4 = document.getElementById("ok2");

function checkUsername() {
var username = el.value;
var password = el_pwd.value;
  if((username.length < 5) & (password.length <= 0)) {
      el2.className = 'warning'; 
      el2.textContent = "Username Not long enough yet..";
      el2.style.color = "red";
      } else {

        el2.textContent = " ";
  }
}

function checkPassword() {
var username = el.value;
var password = el_pwd.value;
   if((username.length >= 5) & (password < 7) ) {

   el2.textContent = "Password MUST be 7 or more characters";
   el2.style.color = "red";
   } else if ((username.length <= 4) & (password.length <= 0))  {

              el2.className = 'warning'; 
              el2.textContent = "Username Not long enough yet..";
              el2.style.color = "red";


   } else {
         el2.textContent = " ";
    }
  }

function usernameOK() {
var username = el.value;
    if(username.length >= 5) {
    el3.style.display="block";
    } else {
      el3.style.display = "none";
   } 
}

function passwordOK() {
var password = el_pwd.value;

if(password.length >= 7) {
el4.style.display="block";
} else {
    el4.style.display = "none";
  }
} 

function feedBack() {
   el2.className = 'tip';
   el2.textContent = "The username MUST be at least 5 characters";
   el2.style.color = "blue";
}




    el.addEventListener("focus", feedBack, false);
    el.addEventListener("blur", checkUsername, false);
    el.addEventListener("blur", usernameOK, false);

    el_pwd.addEventListener("focus", checkPassword, false);
    el_pwd.addEventListener("blur", passwordOK, false);

What I want do be able to do is make a green tick appear next to the password input when a user finishes typing in the required amount of characters.

I have it working so that the green tick appears on "blur", but I'm not sure how to go about the way I would like.

I'm guessing it has something to either do with keyPress or keyDown.

here is the jsfiddle to better understand what I am trying to achieve:

http://jsfiddle.net/addiosamigo/89zfo94m/6/

sorry its a bit clunky (I've asked over at code review what I can do to make it more functional) but I am still learning.

any input would be greatly appreciated!

添加侦听器时,只需用“ keyup”替换“ blur”:

el.addEventListener("keyup", checkUsername, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM