Abdallah El-Rashedy
Abdallah El-Rashedy

Reputation: 871

How to make notice while typing less than minimum length in the input in javascript

I am trying to make the bottom border of input to be red in colour when the lengths of value is less than 3 letters and green if more than 3

function pclck1() {
  "use strict";
  var x = document.getElementById("fname").value;
  if (x.length >= 2) {
    document.getElementById("fname").style.borderBottomColor = "#0d0";
  } else {
    document.getElementById("fname").style.borderBottomColor = "#f00";
  }
}
<input id="fname" type="text" placeholder="Type Here!" onkeypress="pclck1()">

It is working while typing, but after using backspace and delete the letters until the length of the value become 2 or 1 letters or empty the border bottom is still green.

Upvotes: 3

Views: 485

Answers (3)

user9315861
user9315861

Reputation:

There is no need to write any JavaScript at all here. You can do this in pure CSS, using the :invalid pseudo-class together with the pattern attribute.

input { border-bottom-color: green; }
input:invalid { border-bottom-color: red; }
<input id="fname" type="text" placeholder="Type Here!" pattern=".{3,}" required>

Upvotes: 1

Abdallah El-Rashedy
Abdallah El-Rashedy

Reputation: 871

Change onkeypress="pclck1()" to oninput="pclck1()" – NewToJS

It's worked!!

function pclck1() {
    "use strict";
    var x = document.getElementById("fname").value;
    if (x.length < 3) {
    document.getElementById("fname").style.borderBottomColor = "#f00";
    } else {
        document.getElementById("fname").style.borderBottomColor = "#0d0";
    }
}
<input id="fname" type="text" placeholder="Type Here!" oninput="pclck1()">

Thank you NewToJS

Upvotes: 1

Abin Thaha
Abin Thaha

Reputation: 4633

Try this.

I just changed the event onkeypress to onkeyup. Both are different in a way that, onkeypress will work when you press a key. But the onkeyup will work when we release a key after pressing

function pclck1() {
    "use strict";
    var x = document.getElementById("fname").value;
    if (x.length >= 3) {
        document.getElementById("fname").style.borderBottomColor = "#0d0";
    } else {
        document.getElementById("fname").style.borderBottomColor = "#f00";
    }
}
<input id="fname" type="text" placeholder="Type Here!" onkeyup="pclck1()">

Upvotes: 2

Related Questions