I'm setting up a form, is it possible to make a textstring act like a checkbox and for example highlight it when clicked, without actually showing the checkbox?
edit:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function(){
$('.fake-check').on('click',function(){
if($(this).hasClass('checked')){
$(this).removeClass('checked').children('input').val('');
}else{
$(this).addClass('checked').children('input').val($(this).data('val'));
}
});
});
</script>
<link href="test.css" rel="stylesheet" type="text/css" />
<a class="fake-check" data-val="somevalue">Something<input type="text" name="somefield"></a>
Yes, given the following HTML:
<input type="checkbox" id="test" /><label for="test">Click to check</label>
And the CSS:
label {
color: #f00;
}
input {
display: none;
}
input[type=checkbox]:checked + label {
color: #0f0;
}
label {
color: #f00;
}
input {
display: none;
}
input[type=checkbox]:checked + label {
color: #0f0;
}
<input type="checkbox" id="test" checked/>
<label for="test">Click to check</label>
JS Fiddle demo.
This is, of course, dependent on browsers implementing the :checked pseudo-class.
I've used the attribute-equals notation to specify the label elements that follow a checked input of type="checkbox", but as only a checkbox or radio can be selected, that specificity might be safely omitted.
You can also, in compliant browsers, use the same approach in concert with the ::after pseudo-element and its content property, change the text to reflect the state of the checkbox. For example, with the following HTML:
<input type="checkbox" id="test" /><label for="test">Click to</label>
And the CSS:
label {
color: #f00;
}
input {
display: none;
}
input[type=checkbox]:checked + label {
color: #0f0;
}
input[type=checkbox] + label::after {
content: ' check';
}
input[type=checkbox]:checked + label::after {
content: ' uncheck';
}
label {
color: #f00;
}
input {
display: none;
}
input[type=checkbox]:checked + label {
color: #0f0;
}
input[type=checkbox] + label::after {
content: ' check';
}
input[type=checkbox]:checked + label::after {
content: ' uncheck';
}
<input type="checkbox" id="test" checked/>
<label for="test">Click to</label>
References:
Adjacent-sibling (+) combinator.
::before`::after` pseudo-elements.
:checked pseudo-class.
This will work, but only on CSS3 browsers:
<input type="checkbox" id="a" name="a" class="hideMe"> <label for="a">Something</label>
.hideMe {
height:0;
width:0;
visibility:hidden;
}
input:checked + label {
background-color:#e0e0e0
}
You could use jQuery and do this pretty easily:
HTML:
<a class="fake-check" data-val="somevalue">
Something
<input type="hidden" name="somefield">
</a>
CSS:
.checked { background: red; }
JavaScript:
$('.fake-check').on('click',function(){
if($(this).hasClass('checked')){
$(this).removeClass('checked').children('input').val('');
}else{
$(this).addClass('checked').children('input').val($(this).data('val'));
}
});
Here's the fiddle: http://jsfiddle.net/vZVNC/
Try this code
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript">
var is_highlighted = false;
function textclicked(text){
if(is_highlighted == false){
text.style.background = '#FFFF99';
is_highlighted = true;
}
else{
text.style.background = 'none';
is_highlighted = false;
}
}
</script>
</head>
<body>
<a style="cursor:pointer;" onclick="javascript:textclicked(this)">some text which act like checkbox</a>
</body>
</html>
Related
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>
Is there anyway to convert the #HTML.Checkboxfor into toggle html button?
I have refer the toggle button style from https://www.w3schools.com/howto/howto_css_switch.asp
Currently its working by using :
#Html.CheckBoxFor(model => model.IsEnabled, new { #checked = "checked", #Name = "DelegateChkBox" })
Changed to:
<td class="slider-td">
<label class="switch">
<input name="DelegateChkBox" id="IsEnabled" type="checkbox" value="true" data-val-required="The IsEnabled field is required." data-val="true" data-bind="checked: IsEnabled">
<div class="slider round"></div>
</label>
</td>
The toggle button only works and postback to controller if it's CHECKED:
else it won't postback to controller by default UNCHECKED :
Any help will be appreciated!
Thanks!
Based from some experiments and findings, I found that you need to include hidden field generated by the helper (Html.CheckBoxFor) as shown by styling below:
<style type="text/css">
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {display:none;}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
}
/* include generated hidden field here */
input[type="checkbox"]:checked + input[type="hidden"] + .slider,
input[type="checkbox"]:checked + .slider {
background-color: #2196F3;
}
/* include generated hidden field here */
input[type="checkbox"]:focus + input[type="hidden"] + .slider,
input[type="checkbox"]:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
/* include generated hidden field here */
input[type="checkbox"]:checked + input[type="hidden"] + .slider:before,
input[type="checkbox"]:checked + .slider:before {
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
</style>
View usage example (just change <input type="checkbox" /> to #Html.CheckBoxFor):
<label class="switch">
#Html.CheckBoxFor(model => model.IsEnabled)
<div class="slider round">
</div>
</label>
To ensure the checkbox is being checked in client-side before doing postback, you can use jQuery code below:
// change event may modified to other events
$("#IsEnabled").change(function () {
// check if checkbox is being checked
// taken from /a/23007488 by Alexandru Chichinete
if ($("#IsEnabled").is(":checked"))
{
// enable form submit
}
});
Demo example: .NET Fiddle
References:
Styling checkboxes in MVC 4
How can I apply a CSS style to Html.CheckBoxFor in MVC 5
#Html.checkboxfor - Get checkbox value using id
This is very simple, I have implemented in my project.
You just need to keep the value of checkbox in a HiddenFor.
#Html.HiddenFor(model => model.IsEnabled, new{#id = "DelegateChkBox"})
Then display your Toggle button in the page. For example,
<td class="slider-td">
<label class="switch">
<input name="DelegateChkBox" id="IsEnabled" type="checkbox" value="true"
data-val-required="The IsEnabled field is required." data-val="true"
data-bind="checked: IsEnabled">
<div class="slider round"></div>
</label>
</td>
So now when user check/uncheck the checkbox, call a jquery method and assign the value to #Html.HiddenFor(..). That's it.
$('#IsEnabled').change(function(){
if($(this).val()==true)
{
$('#DelegateChkBox').val(true);
}
else
{
$('#DelegateChkBox').val(false);
}
})
Please check once this if ($("this").is(":checked")) instead if($(this).val()==true) and assign the value accordingly. Little busy, could not check my code :)
That's it. Now when you post back your page, you already set value to your IsEnabled field.
In Get method you have to do like the same. You just need to check the value of your HiddenFor() and take that value and assign to your HTML Toggle button in pageload event of js.
$(function() {
if($('#DelegateChkBox').val()== true)
{
$('#IsEnabled').prop("disabled", false);
}
else
{
$('#IsEnabled').prop("disabled", true);
}
});
That's it. Please change the HTML accordingly.
I can have a tri-state checkbox with indeterminate, but I need to rotate 4 states. So how can I make something to look like a quad state checkbox? Is my only option to create a set of images to look like a checkbox with various icons or is there a more elegant way?
You can achieve similar effect (cycled state something) with radio buttons and a bit of CSS (CSS3), without JavaScript:
.cyclestate {
display: inline-grid;
}
.cyclestate label {
grid-area: 1 / 1;
background-color: white;
color: black;
z-index: 0;
opacity: 0;
}
.cyclestate input {
position: absolute;
z-index: -1;
}
.cyclestate input:checked + label {
opacity: 1;
}
.cyclestate input:first-of-type + label {
z-index: 2;
}
.cyclestate input:checked + label + input + label {
opacity: 0;
z-index: 2;
}
/* -- Unrelated and accessibility -- */
.cyclestate { border: none; padding: 0; }
.cyclestate legend { position: absolute; }
.cyclestate label { padding: 1em; text-align: center; display: inline-block; cursor: pointer; user-select: none;
}
.cyclestate label::before { content: '← '; }
.cyclestate label::after { content: ' →'; }
.cyclestate label::before, label::after { color: transparent; }
.cyclestate input:focus-visible + label { outline: solid; }
.cyclestate input:focus-visible + label::before,
.cyclestate input:focus-visible + label::after { color: currentcolor; }
:root { background: dimgray; color: snow; }
:link { color: aqua; } :visited { color: lime; }
<fieldset class="cyclestate" id="x">
<legend>Pick a number</legend>
<input id="one" type="radio" name="r" checked>
<label for="one">One</label>
<input id="two" type="radio" name="r">
<label for="two">Two</label>
<input id="three" type="radio" name="r">
<label for="three">Two Plus One</label>
<input id="four" type="radio" name="r">
<label for="four">Four</label>
</fieldset>
<p><button onclick="x.classList.toggle('cyclestate')">Toggle condenseness ↑</button>
Basically this approach overlays labels over each other (leveraging quite modern CSS techniques (grid)) and makes label of the NEXT unchecked input transparent and raised above all others. In effect what is visible is checked input's label, but click / tap events are captured by that transparent sibling overlay. This preserves semantics and accessibility.
(Caution: haven't thoroughly tested with screen readers nor older browsers.)
Original 2015 snippet with really dubious accessibility, use with caution (or better do not use at all):
.cyclestate input:not(b),
.cyclestate input:not(b) + label {
display: none;
}
.cyclestate input:checked + label {
display: inline-block;
width: 4em;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-webkit-appearance: button;
-moz-appearance: button;
}
<span class="cyclestate">
<input type="radio" name="foo" value="one" id="one" checked>
<label for="two">one</label>
<input type="radio" name="foo" value="two" id="two">
<label for="three">two</label>
<input type="radio" name="foo" value="three" id="three">
<label for="four">three</label>
<input type="radio" name="foo" value="four" id="four">
<label for="one">four</label>
</span>
With this you'll have space-conserving visual representation of multiple state at one place and readable value on the server side.
Be warned that such usage of label is a kinda exploit: label targets different input than it describes.
A checkbox can be made to look like it can have three states, but it will truly only ever have two.
Also, the "indeterminate" visual state is not reachable from the default user interface and has to be triggered programatically:
var box = document.getElementById('box'),
checked = document.getElementById('checked'),
indet = document.getElementById('indet');
var update = function()
{
checked.textContent = box.checked;
indet.textContent = box.indeterminate;
};
box.addEventListener('click', update);
document.getElementById('a').addEventListener('click', function()
{
box.checked = true;
update();
});
document.getElementById('b').addEventListener('click', function()
{
box.checked = false;
update();
});
document.getElementById('c').addEventListener('click', function()
{
box.indeterminate = true;
update();
});
document.getElementById('d').addEventListener('click', function()
{
box.indeterminate = false;
update();
});
<input type="checkbox" id="box"><br>
<button id="a">On</button> <button id="b">Off</button><br>
<button id="c">Indeterminate</button> <button id="d">Clear indeterminate</button>
<div>box.checked: <span id="checked"></span></div>
<div>box.indeterminate: <span id="indet"></span></div>
So to answer your question:
There is no native way to add a fourth visual (yet even actual) state to a checkbox, but this does not mean that you have to resort to images.
It's easy enough to style an element to look like a checkbox and use some JS to simulate a state rotation:
var state = 0;
var toggle = document.getElementById('toggle');
toggle.addEventListener('click', function()
{
state = (state + 1) % 4;
toggle.className = 'state' + state;
});
#toggle
{
border: solid 1px #666;
border-radius: 3px;
width: 14px;
height: 14px;
}
.state0
{
background: linear-gradient(#DDD, #FFF);
}
.state1
{
background: linear-gradient(#F00, #C00);
}
.state2
{
background: linear-gradient(#FF0, #CC0);
}
.state3
{
background: linear-gradient(#0F0, #0A0);
}
<div id="toggle" class="state0"></div>
But in the end you will have to use something other than actual checkboxes.
Apart from that, having a checkbox-like thing with more that two states is really counter-intuitive, and I kindly ask you to go with something that was made for multiple states, like radio buttons or a dropdown list.
It's not possible today. For others reading, a good reference about the using the three states including indeterminate: https://css-tricks.com/indeterminate-checkboxes/
You'll need to create a different solution using your own icons and in a sense create a custom form control. A possible design that fulfills your need to have multiple states:
Use a list of icons, like the star system in Gmail. When the star is clicked in Gmail it changes color and eventually after enough clicks (up to 10 I think) other icons like exclamation point and checkmark begin displaying.
Associate your different state requirements with the currently used icon (or index of the underlying icon list).
<!doctype html>
<html>
<style>
input:focus {
background: yellow;
}
div:focus {
background: gray;
}
</style>
**This section must be highlighted whenever i run the code**
<div>
SOME TEXT<input type = 'text' autofocus>
</div>
<div>
SOME TEXT <input type = 'text'>
</div>
</html>
Hi i tried something using jQuery, though there may be other ways to reach this result.
First i've made a class .gray which i use in the jquery part. And if you use this be sure to include <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
CSS
input:focus {
background: yellow;
}
.gray {
background:gray;
}
jQuery
$('input').blur(function(){
$('input').parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});
jsFiddle
If you want you can replace the remove/addClass by css('background', 'gray');
note this may not be supported in older browsers especially older versions of IE (below 10)
input:focus {
background: yellow;
}
.gray {
background: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('input').blur(function() {
$('input').parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});
});
</script>
<div>
SOME TEXT
<input type="text" value="" autofocus>
</div>
<div>
SOME TEXT
<input type="text" value="">
</div
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 />