How do I simulate placeholder functionality on input date field? - html

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 />

Related

Is there a way to clear an input type="number" like when using type="search"

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>

How to change date format to dd/mm/yyyy in html input

I want to change the date format mm/dd/yyyy to dd/mm/yyyy in the input field.
My input field :
<input type="date">
There is no way to change the default date type input except using CSS and js
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")
input {
position: relative;
width: 150px; height: 20px;
color: white;
}
input:before {
position: absolute;
top: 3px; left: 3px;
content: attr(data-date);
display: inline-block;
color: black;
}
input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {
display: none;
}
input::-webkit-calendar-picker-indicator {
position: absolute;
top: 3px;
right: 0;
color: black;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<input type="date" data-date="" data-date-format="DD/MM/YYYY" value="2020-08-29">
There is no native way of doing that, but here is my HTML + JS solution:
<script>
function DDMMYYYY(value, event) {
let newValue = value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');
const dayOrMonth = (index) => index % 2 === 1 && index < 4;
// on delete key.
if (!event.data) {
return value;
}
return newValue.split('').map((v, i) => dayOrMonth(i) ? v + '/' : v).join('');;
}
</script>
<input type="tel" maxlength="10" placeholder="dd/mm/yyyy"
oninput="this.value = DDMMYYYY(this.value, event)" />
It uses the native HTML "oninput" method so the user don't see anything blinking.
Using "type=tel" it opens a number keyboard on any mobile device.
Basically it's adding '/' after the day and the month and deleting everything else.
Hope it will help someone in the future :)

How to style the parent label of a checked radio input

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&#39t 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>

Color Change after Field Entry - CSS

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

HTML5 <input> tag type ="time"

I use html5 input tag like this:
<input type="time" name="usr_time" value="19:47:13">
But it is invalid value when I submit.
Besides, I cannot change the second in that box, it is disable.
Can someone explain it?
Try to set the step attribute. If it isn't detailed enough, you can also use float values for it.
<input type="time" step="1" />
http://www.w3.org/TR/html-markup/input.time.html
<input type="time" name="usr_time" value="19:47:AM/PM">
Here, value="1:47:AM" so you cannot change the seconds , it is in 12 hours format and if we add step=1 as mentioned above then value="1:47:55:AM".
Since this is only (for this time) supported in MS Edge and Chrome I wrote a tiny component — Timepicker — that you can easily use for major browsers.
The usage is like this:
var timepicker = new TimePicker('time', {
lang: 'en',
theme: 'dark'
});
var input = document.getElementById('time');
timepicker.on('change', function(evt) {
var value = (evt.hour || '00') + ':' + (evt.minute || '00');
evt.element.value = value;
});
body {
font: 1.2em/1.3 sans-serif;
color: #222;
font-weight: 400;
padding: 5px;
margin: 0;
background: linear-gradient(#efefef, #999) fixed;
}
input {
padding: 5px 0;
font-size: 1.5em;
font-family: inherit;
width: 100px;
}
<script src="http://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js"></script>
<link href="http://cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet"/>
<div>
<input type="text" id="time" placeholder="Time">
</div>