Jepf
Jepf

Reputation: 83

Remove Border Color if Empty Value for Input

Need help to fix the issue with to remove border color on Input value.

Once user enter value in input border color will triger but when there is no value the border color should change to inherit color.

Thank you in advance.

var minLength = 9;
var maxLength = 12;
$(document).ready(function(){
  var altNumberVal = $('#AlternateNumber');
    altNumberVal.on('keydown keyup change', function(){
        var char = $(this).val();
        var charLength = $(this).val().length;
        if(charLength < minLength){
          altNumberVal.css("border-color","red");
        }
      else if(charLength > maxLength){
            $(this).val(char.substring(0, maxLength));
        }
      else{
            altNumberVal.css("border-color","inherit");
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<input id="AlternateNumber" placeholder="1234"></input>

Upvotes: 0

Views: 410

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18975

You need add condition to check input is not empty charLength > 0

if(charLength < minLength && charLength > 0){}

var minLength = 9;
var maxLength = 12;
$(document).ready(function(){
  var altNumberVal = $('#AlternateNumber');
    altNumberVal.on('keydown keyup change', function(){
        var char = $(this).val();
        var charLength = $(this).val().length;
        if(charLength < minLength && charLength > 0){
          altNumberVal.css("border-color","red");
        }
      else if(charLength > maxLength){
            $(this).val(char.substring(0, maxLength));
        }
      else{
          
            altNumberVal.css("border-color","inherit");
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<input id="AlternateNumber" placeholder="1234"></input>

Upvotes: 1

Related Questions