Background color of required field - html

I am using the required attribute on certain fields in a form. When form is submitted, required fields that are not filled out get the standard red border around them. Is there a way to also change the background color of the required field that is not filled out after submitting? Here is just a sample textbox that I am using with the required attribute:
<input id="LastName" name="LastName" type="text" placeholder="Last Name" required/>

You can use CSS attribute selector like so:
input[required] {
background-color: red;
}
<input id="LastName" name="LastName" type="text" placeholder="Last Name"
required/>
This will select inputs with required attributes. Now, you can apply this with some simple JavaScript to achieve the desired effect:
var submit_button = document.getElementById("submit_button");
submit_button.addEventListener("click", function(e) {
var required = document.querySelectorAll("input[required]");
required.forEach(function(element) {
if(element.value.trim() == "") {
element.style.backgroundColor = "red";
} else {
element.style.backgroundColor = "white";
}
});
});
<input id="FirstName" name="FirstName" type="text" placeholder="First Name" required/>
<input id="LastName" name="LastName" type="text" placeholder="Last Name" required/>
<input id="submit_button" type="submit">
What this does is add an event listener when the submit button is clicked. When it is, it uses querySelectorAll to get all the inputs that match the CSS attribute selector, input[required]. Next, it does a for-each loop over the returned list of elements. Finally, it checks each inputs value, trimmed, to makes sure there's some content in there (spaces don't count). If there's nothing in the input, it sets the background color to red.
Notes:
You can tweak it as you like, make sure to cancel whatever event you are handling if the inputs are invalid, and you can add classes for styles instead of using element.style.<style>.

You can change it using css as mentioned in some comments above, if it doesn't work then check whether parent background-color attribute is set, in that case you can use !important tag to enforce for the child.

Hello you can try this by basic Css
:required {
background: red;
}
Or using jQuery easily it will work dynamically On button click the background color will be red hope it helps.
the html code
<input id="LastName" name="LastName" type="text" placeholder="Last Name"
required/>
<input id="sub" type="button">
and the jquery code
<script>
$('#sub').click(function(){
$('#LastName').each(function() {
if($(this).val() == '') {
$(this).css('background-color' , '#FF0000');
$(this).attr("placeholder", "Required");
}
});
});
</script>
But if you want to do this for an entire form then it will be something like below
<script>
$('#sub').click(function(e){ //submit button name
e.preventDefault()
$('.required').each(function() { //a constant class for evert input item
if($(this).val() == '') {
$(this).css('background-color' , '#FF0000');
$(this).attr("placeholder", "Required");
}
});
});
</sctript>
see the below fiddle
required Fiddle
must add inside head jQuery Library
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
</head>

input[type="text"],lastname {
background-color : red;
}

body input:focus:required:invalid,
body textarea:focus:required:invalid {
color: green;
}

Related

Make either one HTML input field required using CSS

Is it possible to make either loginid or email as required, just by using CSS or HTML (instead of using Javascript)?
<html>
<body>
<form>
<!-- Atleast one field should be filled by user -->
<label>loginid</label>
<input required>
<label>email</label>
<input required>
</form>
</body>
</html>
Sorry, but it is not possible to use only CSS and HTML to make only one of the two fields "loginid" or "email" mandatory.
This type of functionality would require the use of JavaScript or other server-side technologies. Using :invalid and :valid with the required attribute is useful for form validation, but not for the logic of making specific fields mandatory.
Here is an example of how to make only one of "loginid" or "email" mandatory using JavaScript:
//This code checks if both the "loginid" and "email" fields are blank when the "Submit" button is clicked. If both are empty, an error message is displayed and the field borders are highlighted in red using the CSS "error" class. Otherwise, the "error" class is removed and the form is submitted.
document.getElementById("submitBtn").addEventListener("click", function(event) {
event.preventDefault();
var loginid = document.getElementById("loginid").value;
var email = document.getElementById("email").value;
if (!loginid && !email) {
document.getElementById("loginid").classList.add("error");
document.getElementById("email").classList.add("error");
alert("Either Login ID or Email is required");
} else {
document.getElementById("loginid").classList.remove("error");
document.getElementById("email").classList.remove("error");
// submit the form
}
});
.error {
border: 1px solid red;
}
<div>
<label for="loginid">Login ID:</label>
<input type="text" id="loginid">
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email">
</div>
<button type="submit" id="submitBtn">Submit</button>

Why space in input checkValidity is true?

<input type="text" required>
$('input').blur(function () {
console.log($('input')[0].checkValidity());
});
When I typed a space, the console gives a true. This is very confuse...
Attibute required checks only if there is any character in input (also whitespaces).
If you want to check against blanks you could use pattern.
<input type="text" pattern="\S+" required>
you can use the html5 pattern
i give you an example but you can put what you want
$('input').blur(function () {
console.log($('input')[0].checkValidity());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- this pattern don't allow to put a space in th input-->
<input type="text" pattern="^((?!\s).)*$" required>

Hide label for input without attribute "required" (float label)

I have this code:
<span class="field">
<input type="text" id="first-name" placeholder="First Name" required />
<label for="first-name">First Name</label>
</span>
<span class="field">
<input type="text" id="last-name" placeholder="Last Name" />
<label for="last-name">Last Name</label>
</span>
Label for the second input ("Last Name") is visible from the beginning and not only on focus like the "First Name" label. The difference between two inputs is only in attribute "required" which I don't need for the "Last Name" field.
How to make label for input without attribute "required" hidden? I need it to be shown only on focus with the transition effect. The same like this work for "First Name" field.
http://jsfiddle.net/dmitriy_kalmykov/68jmbquy
You could use the adjacent sibling selector. Add the following code to your CSS file.
input[required] + label {
display: none;
}
What about using required for the last-name field too, but overwriting the required attribute for the last-name input by javascript while submiting the form.
document.getElementById("last-name").required = false;
I know this question was asked 9 month ago, but this can help somebody in future.
I guess you can't submit the form because all fields with float labels should be with the required attribute.If you leave a field empty, the form won't submit. If you remove the attribute, the label is visible and you can submit the form, but the idea of floating labels is ruined.
If I am correct, then try this code:
$( document ).ready(function() {
$('#sub-btn').click(function validateForm() {
var isValid = true;
$('.field').each(function() {
if ( $(this).val() === '' )
$(this).removeAttr("required");
});
return isValid;
});
});
It works for me. You should set the submit button with id="sub-btn" so when you click it, it will clean the required properties.

If checkbox is checked add new input box [duplicate]

This question already has answers here:
Show box or input box on checked box
(2 answers)
Closed 8 years ago.
I have a form like this
<form >
<input type="text" placeholder="First Name" required id="fname" name="fname"/>
<input type="text" placeholder="Last Name" required id="lname" name="lname"/>
<input type="checkbox" placeholder="Maiden Name" id="Maiden Name" name="chkname"/>
<input type="hidden" placeholder="Maiden Name" id="mname" name="mname"/>
...
</form>
and if the checkbox is checked then the maiden name input box should be visible, can anyone help me with this.
In this instance, it's possible to do this without JavaScript, just use the :checked pseudo class:
EXAMPLE HERE
#mname {
display:none;
}
#maidenname:checked ~ #mname {
display:block;
}
Use either the general sibling combinator, ~, or the adjacent sibling combinator +, to change the display of the input element when the checkbox element is toggled. This of course assumes that the checkbox precedes the input element in the DOM.
If you would rather use JavaScript, you could use the following:
JS EXAMPLE HERE
var checkbox = document.getElementById('maidenname');
var input = document.getElementById('mname');
checkbox.addEventListener('click', function () {
if (input.style.display != 'block') {
input.style.display = 'block';
} else {
input.style.display = '';
}
});
Alternatively, if you would rather add an input element to the DOM (as your title implies), rather than changing the visibility of it, you could use something like this:
ALTERNATIVE JS EXAMPLE HERE
var checkbox = document.getElementById('maidenname');
checkbox.addEventListener('click', function () {
if (document.getElementById('mn')) {
document.getElementById('mn').remove();
} else {
var input = document.createElement("input");
input.id = 'mn';
input.type = 'text';
input.placeholder = 'Maiden Name';
document.body.appendChild(input);
}
});
you should not use maiden name input box as type="hidden". Use it as below:
<input type="text" style=" display:none" placeholder="Maiden Name" id="mname" name="mname"/>
Call function to toggle display on click of checkbox:
<input onchange="showHideControl();" type="checkbox" placeholder="Maiden Name" id="Maiden Name" name="chkname"/>
Toggle maiden name input box:
function showHideControl()
{
$('#mname').toggle();
}
You can do it using pure javascript, like so:
<form id=frmMain name=frmMain>
<input type="text" placeholder="First Name" required id="fname" name="fname"/>
<input type="text" placeholder="Last Name" required id="lname" name="lname"/>
<input type="checkbox" placeholder="Maiden Name" id="chkname" name="chkname" onclick=javascript:document.frmMain.mname.hidden=!document.frmMain.chkname.checked; />
<input type="input" hidden=true placeholder="Maiden Name" id="mname" name="mname"/>
...
</form>

Is there a minlength validation attribute in HTML?

It seems the minlength attribute for an <input> field doesn't work.
Is there any other attribute in HTML with the help of which I can set the minimal length of a value for fields?
You can use the pattern attribute. The required attribute is also needed, otherwise an input field with an empty value will be excluded from constraint validation.
<input pattern=".{3,}" required title="3 characters minimum">
<input pattern=".{5,10}" required title="5 to 10 characters">
If you want to create the option to use the pattern for "empty, or minimum length", you could do the following:
<input pattern=".{0}|.{5,10}" required title="Either 0 OR (5 to 10 chars)">
<input pattern=".{0}|.{8,}" required title="Either 0 OR (8 chars minimum)">
There is a minlength property in the HTML5 specification now, as well as the validity.tooShort interface.
Both are now enabled in recent versions of all modern browsers. For details, see https://caniuse.com/#search=minlength.
Here is HTML5-only solution (if you want minlength 5, maxlength 10 character validation)
http://jsfiddle.net/xhqsB/102/
<form>
<input pattern=".{5,10}">
<input type="submit" value="Check"></input>
</form>
Yes, there it is. It's like maxlength. W3.org documentation:
http://www.w3.org/TR/html5/forms.html#attr-fe-minlength
In case minlength doesn't work, use the pattern attribute as mentioned by #Pumbaa80 for the input tag.
For textarea:
For setting max; use maxlength and for min go to this link.
You will find here both for max and min.
I used maxlength and minlength with or without required and it worked for me very well for HTML5.
<input id="passcode" type="password" minlength="8" maxlength="10">
`
minlength attribute is now widely supported in most of the browsers.
<input type="text" minlength="2" required>
But, as with other HTML5 features, IE11 is missing from this panorama. So, if you have a wide IE11 user base, consider using the pattern HTML5 attribute that is supported almost across the board in most browsers (including IE11).
To have a nice and uniform implementation and maybe extensible or dynamic (based on the framework that generate your HTML), I would vote for the pattern attribute:
<input type="text" pattern=".{2,}" required>
There is still a small usability catch when using pattern. The user will see a non-intuitive (very generic) error/warning message when using pattern. See this jsfiddle or below:
<h3>In each form type 1 character and press submit</h3>
</h2>
<form action="#">
Input with minlength: <input type="text" minlength="2" required name="i1">
<input type="submit" value="Submit">
</form>
<br>
<form action="#">
Input with patern: <input type="text" pattern=".{2,}" required name="i1">
<input type="submit" value="Submit">
</form>
For example, in Chrome (but similar in most browsers), you will get the following error messages:
Please lengthen this text to 2 characters or more (you are currently using 1 character)
by using minlength and
Please match the format requested
by using pattern.
I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:
autocomplete="off"
<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />
The minLength attribute (unlike maxLength) does not exist natively in HTML5. However, there a some ways to validate a field if it contains less than x characters.
An example is given using jQuery at this link: http://docs.jquery.com/Plugins/Validation/Methods/minlength
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});;
</script>
<script>
$(document).ready(function(){
$("#myform").validate({
rules: {
field: {
required: true,
minlength: 3
}
}
});
});
</script>
</head>
<body>
<form id="myform">
<label for="field">Required, Minimum length 3: </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" />
</form>
</body>
</html>
Not HTML5, but practical anyway: if you happen to use AngularJS, you can use ng-minlength (or data-ng-minlength) for both inputs and textareas. See also this Plunk.
My solution for textarea using jQuery and combining HTML5 required validation to check the minimum length.
minlength.js
$(document).ready(function(){
$('form textarea[minlength]').on('keyup', function(){
e_len = $(this).val().trim().length
e_min_len = Number($(this).attr('minlength'))
message = e_min_len <= e_len ? '' : e_min_len + ' characters minimum'
this.setCustomValidity(message)
})
})
HTML
<form action="">
<textarea name="test_min_length" id="" cols="30" rows="10" minlength="10"></textarea>
</form>
See http://caniuse.com/#search=minlength. Some browsers may not support this attribute.
If the value of the "type" is one of them:
text, email, search, password, tel, or URL (warning: not include number | no browser support "tel" now - 2017.10)
Use the minlength(/ maxlength) attribute. It specifies the minimum number of characters.
For example,
<input type="text" minlength="11" maxlength="11" pattern="[0-9]*" placeholder="input your phone number">
Or use the "pattern" attribute:
<input type="text" pattern="[0-9]{11}" placeholder="input your phone number">
If the "type" is number, although minlength(/ maxlength) is not be supported, you can use the min(/ max) attribute instead of it.
For example,
<input type="number" min="100" max="999" placeholder="input a three-digit number">
New version:
It extends the use (textarea and input) and fixes bugs.
// Author: Carlos Machado
// Version: 0.2
// Year: 2015
window.onload = function() {
function testFunction(evt) {
var items = this.elements;
for (var j = 0; j < items.length; j++) {
if ((items[j].tagName == "INPUT" || items[j].tagName == "TEXTAREA") && items[j].hasAttribute("minlength")) {
if (items[j].value.length < items[j].getAttribute("minlength") && items[j].value != "") {
items[j].setCustomValidity("The minimum number of characters is " + items[j].getAttribute("minlength") + ".");
items[j].focus();
evt.defaultPrevented;
return;
}
else {
items[j].setCustomValidity('');
}
}
}
}
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !isOpera;
if(!isChrome) {
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testFunction,true);
forms[i].addEventListener('change', testFunction,true);
}
}
}
I wrote this JavaScript code, [minlength.js]:
window.onload = function() {
function testaFunction(evt) {
var elementos = this.elements;
for (var j = 0; j < elementos.length; j++) {
if (elementos[j].tagName == "TEXTAREA" && elementos[j].hasAttribute("minlength")) {
if (elementos[j].value.length < elementos[j].getAttribute("minlength")) {
alert("The textarea control must be at least " + elementos[j].getAttribute("minlength") + " characters.");
evt.preventDefault();
};
}
}
}
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testaFunction, true);
}
}
In my case, in which I validate the most manually and using Firefox (43.0.4), minlength and validity.tooShort are not available unfortunately.
Since I only need to have minimum lengths stored to proceed, an easy and handy way is to assign this value to another valid attribute of the input tag. In that case then, you can use min, max, and step properties from [type="number"] inputs.
Rather than storing those limits in an array it's easier to find it stored in the same input instead of getting the element id to match the array index.
I used max and min then required, and it worked for me very well, but what am not sure is if it is a but coding method.
<input type="text" maxlength="13" name ="idnumber" class="form-control" minlength="13" required>
If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:
// prefix="prefix_text"
// If the user changes the prefix, restore the input with the prefix:
if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
document.getElementById('myInput').value = prefix;
Following #user123444555621 pinned answer.
There is a minlength attribute in HTML5 but for some reason it may not always work as expected.
I had a case where my input type text did not obey the minlength="3" property.
By using the pattern attribute I managed to fix my problem.
Here's an example of using pattern to ensure minlength validation:
const folderNameInput = document.getElementById("folderName");
folderNameInput.addEventListener('focus', setFolderNameValidityMessage);
folderNameInput.addEventListener('input', setFolderNameValidityMessage);
function setFolderNameValidityMessage() {
if (folderNameInput.validity.patternMismatch || folderNameInput.validity.valueMissing) {
folderNameInput.setCustomValidity('The folder name must contain between 3 and 50 chars');
} else {
folderNameInput.setCustomValidity('');
}
}
:root {
--color-main-red: rgb(230, 0, 0);
--color-main-green: rgb(95, 255, 143);
}
form input {
border: 1px solid black;
outline: none;
}
form input:invalid:focus {
border-bottom-color: var(--color-main-red);
box-shadow: 0 2px 0 0 var(--color-main-red);
}
form input:not(:invalid):focus {
border-bottom-color: var(--color-main-green);
box-shadow: 0 2px 0 0 var(--color-main-green);
}
<form>
<input
type="text"
id="folderName"
placeholder="Your folder name"
spellcheck="false"
autocomplete="off"
required
minlength="3"
maxlength="50"
pattern=".{3,50}"
/>
<button type="submit" value="Create folder">Create folder</button>
</form>
For further details, here's the MDN link to the HTML pattern attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern
You can use minlength in input tag or you can regex pattern to check the number of character or even you can take the input and check the length of the character and then you can restrict based upon your requirement.
Smartest Way for maxlength
$("html").on("keydown keyup change", "input", function(){
var maxlength=$(this).attr('maxlength');
if(maxlength){
var value=$(this).val();
if(value.length<=maxlength){
$(this).attr('v',value);
}
else{
$(this).val($(this).attr('v'));
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" maxlength="10">
I've used the follow tag with numbers:
<input type="tel" class="form-control" name="Extension" id="Extension" required maxlength="4" minlength="4" placeholder="4 Digits" />
Add both a maximum and a minimum value. You can specify the range of allowed values:
<input type="number" min="1" max="999" />