find the character quantity of an imput

Asked

Viewed 44 times

-1

1) Create a field and apply the following controls based on the events below:

• In focus event change the input background to yellow.

•When the field loses focus, recover its respective value and: o If the content contained in the field is less than 3 characters, it must have its background changed to red. o If the content contained in the field is 3 characters or more the background must be changed to green.

I’m diffused to understand do the second part.

How to count the characters?

  • See if you can help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length

1 answer

2

Let’s assume your field is this

<input type="text" id="container" name="fname"><br>

javascript provides an event assigner called onfocus and onblur , onfocus works when you focus with your mouse on the element and onblur when you take the focus off

let’s go to an example solving your problem :

First recover your div by id

var inputName = document.getElementById("container");

Now let’s put the onfocus event and put the yellow color in focus

inputName.onfocus = function(){
 InputName.style.backgroundColor = "yellow";
}

Now let’s log onblur and validate the amount of characters

inputName.onblur = function(){
 Name = InputName.value;
 if(Name.length >= 3){
   InputName.style.backgroundColor = "green";
 }
 else{
   InputName.style.backgroundColor = "red";
 }
}

The length function counts the number of characters in a String, so I do the validations according to your example.

I hope I helped , I’m answering my first question , so I may have explained in a way not very easy , accepted tips on how to improve my explanations .

  • Obrgiado @Feliphestival otima explicação.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.