Change input field style when reaches max length limit

我与影子孤独终老i 提交于 2019-12-07 19:12:19

问题


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> 

回答1:


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").




回答2:


You can use something like this:

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



回答3:


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>


来源:https://stackoverflow.com/questions/33018692/change-input-field-style-when-reaches-max-length-limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!