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>
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>
Share
Improve this question
edited Oct 8, 2015 at 14:41
Stickers
78.8k24 gold badges155 silver badges194 bronze badges
asked Oct 8, 2015 at 14:29
Sg72Sg72
1053 silver badges10 bronze badges
1
- 4 This isn't possible because it will not allow text longer than the maxlength in the first place. – TylerH Commented Oct 8, 2015 at 14:34
3 Answers
Reset to default 4You 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 ments the number of characters in your input field can never exceed "maxlength").
You can use something like this:
$("name[usrname]").change(function(){
if($(this).val().length > 10){
$(this).css("color","red");
}
});
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">
<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 :)