Sg72
Sg72

Reputation: 105

Change input field style when reaches max length limit

I created a contact form that has a text input field and maxlength set. I wish that when the characters of the input is greater than 10, then make input field to display in red.

<form action="contact.php">
  Username: <input type="text" name="name" maxlength="10"><br>
  <input type="submit" value="Submit">
</form> 

Upvotes: 2

Views: 7596

Answers (3)

Marco
Marco

Reputation: 63

The attribute maxlength="10" doesn't allow you to insert more than 10 letters. Anyway you can do like this:

    function checkUser(user){
    var number = user.length;
    if(number>10){
    document.getElementById("username").style.borderColor = "red";
   // <!-- document.getElementById("submit").disabled = true;  Disable submit button -->`enter code here`
document.getElementById("maxReached").style.visibility = "visible";
    }else {
document.getElementById("maxReached").style.visibility = "hidden";
document.getElementById("username").style.borderColor = "black";
    }
}
    <html>
    <head>

    </head>
    <body>

    <form action="">
      Username: <input type="text"`enter code here` name="usrname" id="username" oninput="checkUser(this.value);" maxlength="15">
&nbsp;&nbsp;<label id="maxReached" style="visibility: hidden; color:red">Your title is too long</label><br>
      <input type="submit" id="submit" value="Submit">
    </form> 
    </body>
    </html>

I put maxlength="15" only to show you. Hope it's correct for you! You will see it working if you put maxlength over 10. I added a new line in javascript function that allows the script to disable the submit button if the condition is not satisfied if you need it! ;) Bye :)

Upvotes: 1

Fuzzzzel
Fuzzzzel

Reputation: 1773

You could use the selector :invalid in your CSS

input:invalid {
    border: 1px solid #FF0000;
}

This will give all your Input elements a red border, whenever they do not meet the criteria (though as stated in one of the comments the number of characters in your input field can never exceed "maxlength").

Upvotes: 4

Matheus208
Matheus208

Reputation: 1429

You can use something like this:

$("name[usrname]").change(function(){
  if($(this).val().length > 10){
    $(this).css("color","red");
  }
});

Upvotes: 1

Related Questions