Is there any css property which can be used to highlight all the filled fields? Just like we have, on focus css properties.
input[type="text"] {
background-color: white;
}
input[type="text"]:focus {
background-color: red;
}
<input type="text">
I want to make the field background-color green when there is something in the field. Is this possible through CSS? If not CSS, is there any other way?
Certainly you can achieve this with javascript.
The script below will listen for a keyup after the focus has shifted to any one of the <input> fields.
It will then check to see if the respective <input> field is empty.
If it is not, it will change the background of the <input> field to green.
var inputs = document.querySelectorAll('input[type="text"]');
function detectContent() {
if (this.value !== '') {
this.style.backgroundColor = 'green';
this.style.color = 'white';
} else {
this.style.backgroundColor = 'white';
this.style.color = 'black';
}
}
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
input.addEventListener('keyup', detectContent, false);
}
<input type="text" />
<input type="text" />
<input type="text" />
Try this...
$(document).ready(function() {
$(':input').on('input', function() {
if (this.value.length > 0) {
$(this).css('background-color', 'green');
} else {
$(this).css('background-color', '');
}
});
});
input[type="text"] {
background-color: white;
color: #fff;
}
input[type="text"]:focus {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<input type="text">
Related
I have a Bootstrap 4 form with various inputs on some number, some text and others email.
I have already sorted my text inputs by adding the below, which is displaying the 'x' in the input
input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
But I want the same for my 'number' and 'email' inputs
I tried using the below to see if it works, but it doesn't
input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
I have also used the below CSS to remove the arrows when using type='number' and again it works fine
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
Thought I'd ask before I revert to using regex for my number inputs
HTML
<input id="one" class="form-control" type="search" value="Test company name" />
<input id="two" class="form-control" type="number" value="123456" />
<input id="two" class="form-control" type="number" value="12345634" />
As you can see the arrows are not displaying for my number inputs which is what I want.
There is good and bad news. The bad news first: the webkit cancel button is only available to input fields of type search.
The good news: you can create the button yourself.
Copy and paste the following CSS:
.close-button {
color: #1e52e3;
font-size: 12pt;
font-family: monospace,sans-serif;
font-weight: 600;
position: absolute;
z-index: 2;
display: none;
}
.close-button:hover {
cursor: pointer;
}
and change the font-size to what is suitable by trial and error.
Then add this Javascript before the </body> tag in the relevant HTML:
<script>
var fields = document.querySelectorAll('input[type=number],input[type=email]');
fields.forEach(function(input) {
let x = document.createElement('span');
x.classList.add('close-button');
x.innerHTML = 'x';
x.style.left = input.clientWidth - 15;
x.onmousedown = removeContent;
input.parentNode.insertBefore(x, input);
input.oninput = toggleCloseButton;
input.addEventListener( 'focusin', toggleCloseButton);
input.addEventListener( 'focusout', hideCloseButton);
});
function toggleCloseButton() {
if (this.value.length > 0) {
this.previousSibling.style.display = 'block';
} else {
this.previousSibling.style.display = 'none';
}
}
function hideCloseButton() {
this.previousSibling.style.display = 'none';
}
function removeContent(){
this.nextSibling.value = '';
this.nextSibling.focus();
}
</script>
My html page div element is getting changed when I restore down the browser but works fine when I maximize it.
when I click on the password field there is a pop-up window displayed to validate the password complexity and every time it will be displayed next to the password field in full screen mode but it will overlap when I click on password field in restore down mode.
I want that to be showed next to the password field in restore down mode also as how it works in full screen mode.
please help
Please find below the HTML and CSS code attached.
var check = function() {
if (document.getElementById('psw').value ==
document.getElementById('confirmPassword').value) {
document.getElementById('info').style.color = 'green';
document.getElementById('info').innerHTML = 'Matching';
} else {
document.getElementById('info').style.color = 'red';
document.getElementById('info').innerHTML = 'Not Matching';
}
}
function myFunction() {
var x = document.getElementById("psw"), y = document.getElementById("confirmPassword");
if (x.type === "password") {
x.type = "text";
y.type = "text";
} else {
x.type = "password";
y.type = "password";
}
}
var psw = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");
var symbol = document.getElementById("symbol");
// When the user clicks on the password field, show the message box
psw.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// When the user clicks outside of the password field, hide the message box
psw.onblur = function() {
document.getElementById("message").style.display = "none";
}
// When the user starts to type something inside the password field
psw.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(psw.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
// Validate capital letters
var upperCaseLetters = /[A-Z]/g;
if(psw.value.match(upperCaseLetters)) {
capital.classList.remove("invalid");
capital.classList.add("valid");
} else {
capital.classList.remove("valid");
capital.classList.add("invalid");
}
// Validate numbers
var numbers = /[0-9]/g;
if(psw.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if(psw.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
// Validate Symbols
var symbols = /[-!$%^&*()_+|~=`{}[:;<>?,.##\]]/g;
if(psw.value.match(symbols)) {
symbol.classList.remove("invalid");
symbol.classList.add("valid");
} else {
symbol.classList.remove("valid");
symbol.classList.add("invalid");
}
}
/* Style all input fields */
input {
width: 25%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 8px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 6px;
}
#myForm select
{
width: 25%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 8px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
}
/* Style the submit button */
input[type=submit] {
background-color: #4CAF50;
color: white;
}
/* Style the container for inputs */
.container {
background-color: #f1f1f1;
padding: 20px;
}
/* The message box is shown when the user clicks on the password field */
#message {
display:none;
float: left;
background: transparent;
color: #000;
position: absolute;
right: 0;
padding: -2000px;
margin-top: -120px;
margin-right: 200px;
}
#message p {
padding: 1px 35px;
font-size: 14px;
}
/* Add a green text color and a checkmark when the requirements are right */
.valid {
color: green;
}
.valid:before {
position: relative;
left: -35px;
content: "✔";
}
/* Add a red text color and an "x" when the requirements are wrong */
.invalid {
color: red;
}
.invalid:before {
position: relative;
left: -35px;
content: "?";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body bgcolor="#dbddea">
<h2 align="center"><u>Password Change</u></h2>
<p align="center"><marquee><h3>Change the password for unix users.</h3></marquee></p>
<div class="container">
<form>
<div id=myForm align = "center">
<label for="usrname">Select Username</label><br>
<select name="Users">
<option value="test1">test1</option>
<option value="test2">test2</option>
</select>
</div>
<div align= "center">
<input type="password" id="psw" name="psw" onkeyup='check();' placeholder="New Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%^&*_=+-]).{8,}" title="Must contain at least one number, one symbol and one uppercase and lowercase letter, and at least 8 or more characters" required>
<br>
<div id="message" align = "left">
<h4>Password must contain the following:</h4>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
<p id="symbol" class="invalid">A <b>symbol</b></p>
</div>
<input type="password" id="confirmPassword" name="confirmPassword" onkeyup='check();' placeholder="Re-type Password" title="Confirm new password" required>
<br>
<span id='info'></span>
<input type="checkbox" onclick="myFunction()" style="width: 40px;">Show Password
</div>
<div align = "center">
<input type="submit" id="submit" value="Change Password">
</div>
</form>
</div>
</body>
</html>
Plz add this code..
css
#media only screen and (max-width: 1280px) {
#message {
position: relative;
float: none;
margin: 0;
width: 25%;
}
}
Plz modify your css code..
css
#message {
display:none;
width: 25%;
}
HTML
<div class="container">
<form>
<div id=myForm align = "center">
<label for="usrname">Select Username</label><br>
<select name="Users">
<option value="test1">test1</option>
<option value="test2">test2</option>
</select>
</div>
<div align= "center">
<input type="password" id="psw" name="psw" onkeyup='check();' placeholder="New Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%^&*_=+-]).{8,}" title="Must contain at least one number, one symbol and one uppercase and lowercase letter, and at least 8 or more characters" required>
<br>
<input type="password" id="confirmPassword" name="confirmPassword" onkeyup='check();' placeholder="Re-type Password" title="Confirm new password" required>
<br>
<div id="message" align = "left">
<h4>Password must contain the following:</h4>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
<p id="symbol" class="invalid">A <b>symbol</b></p>
</div>
<span id='info'></span>
<input type="checkbox" onclick="myFunction()" style="width: 40px;">Show Password
</div>
<div align = "center">
<input type="submit" id="submit" value="Change Password">
</div>
</form>
</div>
Here are some changes to make it simple.
#message {
display:none;
float: left;
background: transparent;
color: #000;
position: absolute;
right: 0;
padding: -2000px;
margin-top: -120px;
margin-right: 200px;
}
Replace with below CSS
#message {
width: 25%;
}
Make changes in js code as below
psw.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// When the user clicks outside of the password field, hide the message box
psw.onblur = function() {
document.getElementById("message").style.display = "none";
}
Change to
psw.onfocus = function() {
$('#message').slideDown();
}
// When the user clicks outside of the password field, hide the message box
psw.onblur = function() {
$('#message').slideUp();
}
I need to make HTML5 validation rule so:
10 characters
mix of letters and numbers
at least 1 letter
I try something like:
<input maxlength="200" type="text" name="serial" id="serial" required="required" class="form-control input-lg" pattern="[a-fA-F]{1,}[0-9]{10}" title="Wrong Code" placeholder="Security Code" />
but don't work.
You could use <input type="password" pattern="^[a-zA-Z][a-zA-Z0-9-_\.]{1,10}$" required>
Or this (it's a bit longer...):
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
input {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px
}
input[type=button] {
background-color: #4CAF50;
color: white
}
.container {
background-color: #f1f1f1;
padding: 20px
}
#message {
display: none;
position: relative;
margin-top: 10px
}
.valid {
display: none
}
</style>
</head>
<body>
<div class="container">
<form action="/db.php" id="form">
<label for="psw">Password</label>
<input type="password" id="psw" name="psw" required>
<input type="button" value="Submit" onclick="analyze()">
</form>
</div>
<div id="message">
<h3 id="theH3">Your password doesn't contain any of the following:</h3>
<p id="letter" class="invalid">A letter</p>
<p id="number" class="invalid">A number</p>
<p id="length" class="invalid">10 characters</p>
</div>
<script>
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");
var tmp = 0;
myInput.onfocus = function () {
document.getElementById("message").style.display = "block";
}
myInput.onblur = function () {
document.getElementById("message").style.display = "none";
}
myInput.onkeyup = function () {
var lowerCaseLetters = /[a-zA-Z]/g;
if (myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
tmp++;
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
var numbers = /[0-9]/g;
if (myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
tmp++;
} else {
number.classList.remove("valid");
number.classList.add("invalid");
} if (myInput.value.length >= 10) {
length.classList.remove("invalid");
length.classList.add("valid");
tmp++;
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
function analyze() {
var lowerCaseLetters = /[a-zA-Z]/g;
var numbers = /[0-9]/g;
if (lowerCaseLetters.test(myInput.value) && numbers.test(myInput.value))document.getElementById('form').submit();
if(tmp==3){
var message = document.getElementById('theH3')
message.style('display:none;');
}
}
</script>
</body>
</html>
<input maxlength="200" type="text" name="serial" id="serial" required="required" class="form-control input-lg" pattern="^[a-zA-Z][a-zA-Z0-9-_\.]{1,10}$" title="Wrong Code" placeholder="Security Code" />
^[a-zA-Z][a-zA-Z0-9-_\.]{1,10}$
I think you are looking for this website.
URL : http://html5pattern.com/Names
I need to stylize some radio inputs. I tried some solutions from here but none worked for me. Can someone please take a look at this code and tell me what can I do?
This is the HTML:
<div class="controls">
<table>
<tbody>
<tr>
<td>
<label class="radio">
<input type="radio" name="ad_caroserie" value="0">Berlina
</label>
</td>
<td>
<label class="radio">
<input type="radio" name="ad_caroserie" value="1">Break
</label>
</td>
<td>
<label class="radio">
<input type="radio" name="ad_caroserie" value="2">Cabrio
</label>
</td>
</tr>
</tbody>
</table>
</div>
And the CSS:
label.radio {
background: #fcb608;
}
.radio input {
display: none;
}
label.radio input[type="radio"]:checked + label {
background: #000 !important;
border: 1px solid green;
padding: 2px 10px;
}
The CSS doesn't have the desired effect; Can you please help me?
This is some related excerpts of JS:
//If checkboxes or radio buttons, special treatment
else if (jQ('input[name="'+parentname+'"]').is(':radio') || jQ('input[name="'+parentname+'[]"]').is(':checkbox')) {
var find = false;
var allVals = [];
jQ("input:checked").each(function() {
for(var i = 0; i < parentvalues.length; i++) {
if (jQ(this).val() == parentvalues[i] && find == false) {
jQ('#adminForm #f'+child).show();
jQ('#adminForm #row_'+child).show();
find = true;
}
}
});
if (find == false) {
jQ('#adminForm #f'+child).hide();
jQ('#adminForm #row_'+child).hide();
//cleanup child field
if (jQ('#adminForm #f'+child).is(':checkbox') || jQ('#adminForm #f'+child).is(':radio')) {
jQ('#adminForm #f'+child).attr('checked', false);
}
else {
if (cleanValue == true) {
jQ('#adminForm #f'+child).val('');
}
}
}
}
else {
var find = false;
for(var i = 0; i < parentvalues.length; i++) {
if (jQ('#adminForm #f'+parentname).val() == parentvalues[i] && find == false) {
jQ('#adminForm #f'+child).show();
jQ('#adminForm #row_'+child).show();
find = true;
}
}
if(find == false) {
jQ('#adminForm #f'+child).hide();
jQ('#adminForm #row_'+child).hide();
//cleanup child field
if (jQ('#adminForm #f'+child).is(':checkbox') || jQ('#adminForm #f'+child).is(':radio')) {
jQ('#adminForm #f'+child).attr('checked', false);
}
else {
if (cleanValue == true) {
jQ('#adminForm #f'+child).val('');
}
}
}
}
}
function dependency(child,parentname,parentvalue) {
var parentvalues = parentvalue.split(",");
//if checkboxes
jQ('input[name="'+parentname+'[]"]').change(function() {
checkdependency(child,parentname,parentvalues,true);
//if checkboxes
jQ('input[name="'+child+'[]"]').change();
jQ('input[name="'+child+'"]').change();
jQ('#'+child).change();
});
//if buttons radio
jQ('input[name="'+parentname+'"]').change(function() {
checkdependency(child,parentname,parentvalues,true);
//if checkboxes
jQ('input[name="'+child+'[]"]').change();
jQ('input[name="'+child+'"]').change();
jQ('#'+child).change();
});
jQ('#f'+parentname).click(function() {
checkdependency(child,parentname,parentvalues,true);
//if checkboxes
jQ('input[name="'+child+'[]"]').change();
jQ('input[name="'+child+'"]').change();
jQ('#f'+child).change();
});
checkdependency(child,parentname,parentvalues,false);
}
A possibility
At my time of posting, I am not exactly sure what the desired layout should be, but there is one specific problem in the attempted CSS that needs to be addressed.
The adjacent siblings selector:
... separates two selectors and matches the second element only if it immediately follows the first element.
If the <input> is a child of the <label>, it isn't adjacent, so while:
label.radio input[type="radio"]:checked + label
is looking for a label immediately following a :checked input inside a label with the class .radio, nothing like that exists.
To alter the styling of the label in this case, would require a selector that affected the parent, which currently isn't possible.
So, to select the label of the :checked input, we need the label to be adjacent, not the parent.
We can use the for="id" attribute:
A <label> can be associated with a control either by placing the control element inside the <label> element, or by using the for attribute.
As I said, I'm not exactly sure what the desired layout should be, but here's an example using the for attribute, that doesn't look too bad.
div {
display: inline-block;
position: relative;
}
label {
background: #fcb608;
padding: 2px 10px 2px 1.5em;
border: 1px solid transparent; /* keeps layout from jumping */
}
input {
position: absolute;
}
input[type="radio"]:checked + label {
background: #000;
border-color: green;
color: white;
}
<div>
<input id="id1" type="radio" name="ad_caroserie" value="0">
<label for="id1" class="radio">Berlina</label>
</div>
<div>
<input id="id2" type="radio" name="ad_caroserie" value="1">
<label for="id2" class="radio">Break</label>
</div>
<div>
<input id="id3" type="radio" name="ad_caroserie" value="2">
<label for="id3" class="radio">Cabrio</label>
</div>
With <input> as a child of <label>
Using a small JavaScript handler listening for changes to the <form>.
If a change is detected, the triggered function checks if an <input type="radio"> was changed, and if so, if it has a <label> as its parentElement.
If that's true, it checks to see if there's an identically named <input type="radio"> that's a child of a <label> element with the class .checked.
If there is, it removes the class from the <label> before applying the same class to the <label> parent of the <input> target that triggered the whole thing.
let form = document.querySelector( "form" );
form.addEventListener( "change", ( evt ) => {
let trg = evt.target,
trg_par = trg.parentElement;
if ( trg.type === "radio" && trg_par &&
trg_par.tagName.toLowerCase() === "label" ) {
let prior = form.querySelector( 'label.checked input[name="' +
trg.name + '"]' );
if ( prior ) {
prior.parentElement.classList.remove( "checked" );
}
trg_par.classList.add( "checked" );
}
}, false );
label {
background: #fcb608;
padding: 2px 10px 2px 0;
border: 1px solid transparent; /* keeps layout from jumping */
}
label.checked {
background: #000;
border-color: green;
color: white;
}
<form>
<label class="radio"><input type="radio" name="ad_caroserie" value="0">Berlina</label>
<label class="radio"><input type="radio" name="ad_caroserie" value="1">Break</label>
<label class="radio"><input type="radio" name="ad_caroserie" value="2">Cabrio</label>
</form>
Without JavaScript things get difficult (per my original explanation of why it's best to use the for attribute in this case).
We can use the appearance property (with prefixes and reasonable support) to effectively hide the user-agent radio GUI, then use the remaining faceless element to build a fake background for the <label>.
This is very hacky and a great deal less dynamic than the default, since some absolute positioning and specific dimensions are required to pull it off.
It kind of works (in most browsers), but is tricky to enforce sitewide.
Something to play around with though :-)
input {
position: absolute;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
width: 5em;
height: 1.5em;
z-index: -1;
background: #fcb608;
border: 1px solid transparent;
margin: -.1em -.8em;
outline: 0;
}
label {
display: inline-block;
width: 5em;
color: white;
text-shadow: 1px 1px 0px black;
}
input[type="radio"]:checked {
background: #000;
border-color: green;
}
<label class="radio"><input type="radio" name="ad_caroserie" value="0">Berlina</label>
<label class="radio"><input type="radio" name="ad_caroserie" value="1">Break</label>
<label class="radio"><input type="radio" name="ad_caroserie" value="2">Cabrio</label>
Just use jQuery with a new css class "selected" something like this:
on start:
$("input[name='ad_caroserie']:checked").parent().addClass("selected");
and onchange:
$('input[type=radio][name=ad_caroserie]').change(function() {
$("input[name='ad_caroserie']").parent().removeClass("selected");
$("input[name='ad_caroserie']:checked").parent().addClass("selected");
// console.log($("input[name='ad_caroserie']:checked").val());
});
After trying so many time with pure HTML and CSS. I am settling with this simple solution with JavaScript. I think this will help.
function check(btn) {
let label = btn.children;
label[0].checked = true;
}
.lib-radio {
color: #1e1e1e;
font-size: 1.0em;
border-radius: 31px;
font-weight: 400;
width: 450px;
height: 40px;
border: 2px solid black;
padding: 0.5em;
font-family: Lato;
margin: 10px 0 0 0;
}
.lib-radio:hover {
background-color: #000;
color: #FFF;
}
<div class="lib-one-input">
<p class="lib-form-label">Select your gender</p>
<div class="lib-radio" onclick="check(this)">
<input id="s1yes" type="radio" name="mcq1" value="male">
<label for="s1yes"> Yes, our researchers authored it</label><br />
</div>
<div class="lib-radio" onclick="check(this)">
<input id="s1no" type="radio" name="mcq1" value="female">
<label for="s1no"> No, we didn't author it </label><br />
</div>
</div>
<form id="button-form">
<fieldset id="button-set">
<label for="button-1">
<input type="radio" id="button-1" name="button-group"/>
</label>
<label for="button-2">
<input type="radio" id="button-2" name="button-group"/>
</label>
<label for="button-3">
<input type="radio" id="button-3" name="button-group"/>
</label>
</fieldset>
</form>
<style>
#button-set label > * {
opacity: 0; <!-- hideing the radio buttons -->
}
</style>
<script>
function setColor(color) {
document.getElementsByName("button-group").forEach(node => {
node.checked === true
? (node.parentElement.style.background = color)
: (node.parentElement.style.background = "rgba(0, 0, 0, 0.5)");
});
}
window.onload = () => {
document.getElementById("button-form").onchange = evt => {
switch (evt.target) {
case document.getElementsById("button-1"):
setColor("rgba(0, 150, 0, 0.5)");
break;
case document.getElementsById("button-2"):
setColor("rgba(250, 200, 0, 0.5)");
break;
case document.getElementsById("button-3"):
setColor("rgba(250, 0, 0, 0.5)");
break;
}
};
};
</script>
It's impossible to use placeholder on date fields but I really need it.
I want two date inputs with texts "From" and "To" on each one as placeholders.
I'm using the following CSS only trick:
input[type="date"]:before {
content: attr(placeholder) !important;
color: #aaa;
margin-right: 0.5em;
}
input[type="date"]:focus:before,
input[type="date"]:valid:before {
content: "";
}
<input type="date" placeholder="Choose a Date" />
use this input attribute events
onfocus="(this.type='date')" onblur="(this.type='text')"
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container mt-3">
<label for="date">Date : </label>
<input placeholder="Your Date" class="form-control" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date">
</div>
You can use CSS's before pseudo.
.dateclass {
width: 100%;
}
.dateclass.placeholderclass::before {
width: 100%;
content: attr(placeholder);
}
.dateclass.placeholderclass:hover::before {
width: 0%;
content: "";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input
type="date"
placeholder="Please specify a date"
onClick="$(this).removeClass('placeholderclass')"
class="dateclass placeholderclass">
FIDDLE
You can do something like this:
<input onfocus="(this.type='date')" class="js-form-control" placeholder="Enter Date">
The HTML5 date input field actually does not support the attribute for placeholder. It will always be ignored by the browser, at least as per the current spec.
As noted here
I'm using this css method in order to simulate placeholder on the input date.
The only thing that need js is to setAttribute of the value, if using React, it works out of the box.
input[type="date"] {
position: relative;
}
input[type="date"]:before {
content: attr(placeholder);
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #fff;
color: rgba(0, 0, 0, 0.65);
pointer-events: none;
line-height: 1.5;
padding: 0 0.5rem;
}
input[type="date"]:focus:before,
input[type="date"]:not([value=""]):before
{
display: none;
}
<input type="date" placeholder="Choose date" value="" onChange="this.setAttribute('value', this.value)" />
The input[type="date"] DOMElement only takes the following value: YYYY-MM-DD, any other format or text with be skipped.
var element = document.querySelectorAll('[placeholder]');
for (var i in element) {
if (element[i].nodeType == 1 && element[i].nodeName == "INPUT") {
element[i].value = element[i].getAttribute('placeholder');
element[i].style.color = "#777";
element[i].onfocus = function(event) {
if (this.value == this.getAttribute('placeholder')) {
this.value = "";
this.style.color = "#000"
};
};
element[i].onblur = function(event) {
if (this.value == "") {
this.value = this.getAttribute('placeholder');
this.style.color = "#777";
}
};
}
}
<input type="text" placeholder="bingo" />
<input type="date" placeholder="2013-01-25" />
In this exact case, with 2 input elements, Pure JavaScript is ~40% ± 10% faster. With 32 input elements, the difference remains the same (~43% ± 10% faster for Pure JS).
Got the most easiest hack for this problem-use this syntax in your HTML-input-tag
<input type="text" id="my_element_id" placeholder="select a date" name="my_element_name" onfocus="(this.type='date')" />
</div>
Try this:
Add a placeholder attribute to your field with the value you want, then add this jQuery:
$('[placeholder]').each(function(){
$(this).val($(this).attr('placeholder'));
}).focus(function(){
if ($(this).val() == $(this).attr('placeholder')) { $(this).val(''); }
}).blur(function(){
if ($(this).val() == '') { $(this).val($(this).attr('placeholder')); }
});
I've not tested it for fields that can't take placeholders but you shouldn't need to change anything in the code at all.
On another note, this code is also a great solution for browsers that don't support the placeholder attribute.
As mentionned here, I've made it work with some ":before" pseudo-class and a small bit of javascript.
Here is the idea :
#myInput:before{ content:"Date of birth"; width:100%; color:#AAA; }
#myInput:focus:before,
#myInput.not_empty:before{ content:none }
Then in javascript, add the "not_empty" class depending on the value in the onChange and onKeyUp events.
You can even add all of this dynamically on every date fields. Check my answer on the other thread for the code.
It's not perfect but it's working well in Chrome and iOS7 webviews. Maybe it could help you.
As i mentioned here
initially set the field type to text.
on focus change it to type date
just use it :
var elementDate = $('input[type="date"]');
$.each(elementDate, (key, value) => {
if (!$(value).val()) {
$(value).css("color", "#777");
}
$(value).on("focus", function (event) {
$(this).css("color", "#000");
});
$(value).on("blur", function (event) {
if (!$(this).val()) {
$(this).css("color", "#777");
}
});
});
Ok, so this is what I have done:
$(document).on('change','#birthday',function(){
if($('#birthday').val()!==''){
$('#birthday').addClass('hasValue');
}else{
$('#birthday').removeClass('hasValue');
}
})
This is to remove the placeholder when a value is given.
input[type="date"]:before {
content: attr(placeholder) !important;
color: #5C5C5C;
margin-right: 0.5em;
}
input[type="date"]:focus:before,
input[type="date"].hasValue:before {
content: "" !important;
margin-right: 0;
}
On focus or if .hasValue, remove the placeholder and its margin.
Using a jQuery (sure you can achieve this with Vanilla. This make sure the date format still the same.
$(function() {
$('.sdate').on('focus', function() {
$(this).attr('type', 'date');
});
$('.sdate').on('blur', function() {
if(!$(this).val()) { // important
$(this).attr('type', 'text');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" class="sdate" placeholder="From">
CSS
input[type="date"] {position: relative;}
input[type="date"]:before {
position: absolute;left: 0px;top: 0px;
content: "Enter DOB";
color: #999;
width: 100%;line-height: 32px;
}
input[type="date"]:valid:before {display: none;}
<input type="date" required />