CSS mandates the inclusion of the required tag on input fields, however it may not always be necessary

Currently, I am using Google Chrome which is vital for my work.

Utilizing CSS and jQuery, I have developed adorable 'placeholders' that transition into labels. You can view the codepen here.

//HTML

 <div class="form-group col-lg-6 field">
  <label for="FirstName" class="col-12">Date without Required tag</label>
  <input type="date" class="form-control col-12"/>
</div>

<div class="form-group col-lg-6 field">
  <label for="FirstName" class="col-12">Date With Required Tag</label>
  <input type="date" class="form-control col-12" required/>
</div>


//CSS

.field > input,
.field > label {
    position: relative;
    display: inline-block;
    width: 100%;
    transition: all 0.3s ease-in-out; /* adding animation */
}
.field > label {
    display: inline-block;
    margin: 0 auto;
    padding: 0 0 5px 7px;
    top: 36px;
    z-index: 1; /* placing label behind input */
}


form input[type="text"],
form input[type="email"],
form input[type="date"] {
    font-size: 1em;
    padding: 0 0 0 7px;
    z-index: 10;
    background: transparent; /* adding transparency */
}

.filled label {
    top: 0;
    font-size: 0.8em;
}

.form-group {
    margin-bottom: .5rem !important;
}


input[type="date"]::-webkit-datetime-edit {
    color: transparent;
    }

input[type="date"]:focus::-webkit-datetime-edit {
    color: black !important;
        }

input[type="date"]:valid::-webkit-datetime-edit {
    color: black;
    }
	
 //JQUERY

 $("form input").on("blur input focus", function() {
        var $field = $(this).closest(".field");
        if (this.value) {
            $field.addClass("filled");
        } else {
            $field.removeClass("filled");
        }
    });


    $("form input").on("focus", function() {
        var $field = $(this).closest(".field");
        if (this) {
            $field.addClass("filled");
        } else {
            $field.removeClass("filled");
        }
    }); 


$('.field > select').on("focus", function () {
    var $field = $(this).closest(".field");
    var $select = $(this).closest("select");

    if (this) {
        $field.addClass("filled");
        $select.removeClass("hiddenText");
    } else {
        $field.removeClass("filled");
    }
});

All input types function perfectly except for 'date'. Without the required tag on a date input, it appears distorted. Despite thorough analysis, I cannot pinpoint any errors in my CSS or jQuery. Any suggestions?

I've attempted modifying the targeted classes and using !important tags with no success. The issue seems peculiar and eludes me completely.

If you have insights on how to make it compatible with Edge or other browsers, bonus points to you. While compatibility across browsers interests me, my primary focus lies elsewhere at the moment.

Answer №1

Transform the default date input to behave like a text input by using this code snippet.

<input type="text" onfocus="(this.type='date')" onfocusout="(this.type='text')" class="form-control col-12"/>

Answer №2

To achieve the desired outcome, insert the following CSS code for the input date field with content set to null and using the ::before selector

input[type="date"]::before { 
    content: '';
    width: 100%;
}

Here is a working example for your reference - https://codepen.io/nagasai/pen/zYOVZXX

$("input").attr('placeholder','');
$("form input").on("blur input focus", function() {
var $field = $(this).closest(".field");
if (this.value) {
$field.addClass("filled");
} else {
$field.removeClass("filled");
});


$("form input").on("focus", function() {
var $field = $(this).closest(".field");
if (this) {
$field.addClass("filled");
} else {
$field.removeClass("filled");
});


    $('.field > select').on("focus", function () {
        var $field = $(this).closest(".field");
        var $select = $(this).closest("select");

        if (this) {
            $field.addClass("filled");
            $select.removeClass("hiddenText");
        } else {
            $field.removeClass("filled");
        }
    });
/*originally "form input" and "form label" rather than ".field > XXX" */
.field > input,
.field > label {
    position: relative;
    display: inline-block;
    width: 100%;
    transition: all 0.3s ease-in-out; /* adding animation */
}
/*originally "form label" rather than ".field > label" */
.field > label {
    display: inline-block;
    margin: 0 auto;
    padding: 0 0 5px 7px;
    top: 36px;
    z-index: 1; /* placing label behind input */
}


form input[type="text"],
form input[type="email"],
form input[type="date"] {
    font-size: 1em;
    padding: 0 0 0 7px;
    z-index: 10;
    background: transparent; /* adding transparency */
}

.filled label {
    top: 0;
    font-size: 0.8em;
}

.form-group {
    margin-bottom: .5rem !important;
}




input[type="date"]::-webkit-datetime-edit {
color: transparent;
    }

input[type="date"]:focus::-webkit-datetime-edit {
color: black !important;
        }

input[type="date"]:valid::-webkit-datetime-edit {
color: black;
    }


input[type="date"]::before { 
content: '';
width: 100%;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<form>
<div class="form-group col-lg-6 field">
  <label for="FirstName" class="col-12">First Name</label>
  <input type="text" class="form-control col-12"/>
</div>
  
 <div class="form-group col-lg-6 field">
  <label for="FirstName" class="col-12">Date without Required tag</label>
  <input type="date" class="form-control col-12"/>
</div>

  
<div class="form-group col-lg-6 field">
  <label for="FirstName" class="col-12">Date With Required Tag</label>
  <input type="date" class="form-control col-12" required/>
</div>
  
</form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing jQuery's .clone() function to duplicate HTML forms with radio buttons will maintain the radio events specific to each cloned element

I'm currently developing front-end forms using Bootstrap, jQuery, HTML, and a Django backend. In one part of the form, users need to input "Software" information and then have the option to upload the software file or provide a URL link to their hoste ...

user1234: I'm interested in decreasing the amount of items shown on the screen when it's smaller

Currently working on the design of the Search page for an online store. I aim to adjust the number of items displayed on the screen gradually as the screen size changes, similar to Amazon's layout. Additionally, I'm looking to rectify the excess ...

Using JQuery: Executing a callback function at the end of each loop following the ajax call

How can I implement a callback for each loop iteration after an AJAX call is completed? Here is my code: Scenario: Suppose I have 3 values - X, Y, Z. Initially, I take the X value, send it to Django views where I use the requests module to retrieve some ...

What is the best way to arrange data within the <th> tag to mimic a row layout?

Is there a way to align text within <th> tags of a table so that it appears in a row-like fashion, rather than up and down? I want the headings to be level with each other. For example, titles like Americas Center, Asheville, ..., Coopersville shoul ...

Incorporate a dynamic PowerPoint presentation directly onto my website

In my situation, on the client side, users can select image files (jpg|png|gif), PDF files, and PPT files which are then stored in a database. When viewing these selected files in the admin panel, I am using conditional statements to display them appropr ...

Pop-up - maintain the initial value

I'm working on a modal using Bootstrap and React. Inside the modal, there's a dropdown with an initial empty option: <select class="form-control" onChange={this.handleSelectCat}> <option disabled selected></option> < ...

Unable to function in simplistic html/php code, 'Require' fails to operate as intended

I am facing an issue while attempting to import a header.php file into my index.php file. For some reason, it is not working as expected. header.php: <!DOCTYPE html> <html> <head></head> <body> <header> & ...

Utilize an Ajax function to call the BOT listening URL within a Web method

My recently developed web application features a submit button that triggers an Ajax call to communicate with the BOT. The code snippet used for the Ajax function is as follows: <script> $(document).ready(function () { $("#btnSend& ...

The transition effects between iOS5 and jquery-mobile can cause brief flickering

I have been struggling to eliminate a bothersome flickering effect on jqmobile transitions when using iOS 5. Despite trying various methods mentioned in other posts, such as -webkit-backface, I have not been able to find a complete solution. Upon closer ob ...

Implementing Conditional Display of Span Tags in React Based on Timer Duration

In my current React project, I am facing an issue with displaying a span tag based on a boolean value. I need assistance in figuring out how to pass a value that can switch between true and false to show or hide the span tag. I tried two different methods ...

JQuery Ajax encounters a 500 error message due to an internal server issue

I'm currently using the jQuery library to send an ajax request to a PHP file. Initially, everything was working perfectly fine with a relative path like this: url:"fetch_term_grades.php", However, when I modified the path to be more specific like th ...

Isotope grid shatters when browser window is resized

My goal is to design a 3-column grid using Twitter Bootstrap and Isotope. However, when I resize the browser to force the layout into a single column mode, Isotope fails and leaves large spaces both vertically and horizontally. Regular Layout Issues in ...

The calendar popup in the angular-bootstrap3-datepicker failed to update during page loading

My current challenge involves implementing a datepicker using the angular-bootstrap3-datepicker library. The date picker is functioning properly, but I am encountering an issue where the calendar months do not refresh when assigning values at page load. It ...

Center align content on small screens using Bootstrap 4

Here is a simple Bootstrap 4 row example: <div class="container"> <div class="row"> <div class="col-md-12 p-2"> <img class="" src="../assets/img/Logo-small.png" alt=&q ...

Troubles encountered in retrieving values from various <select>/<option> elements

Having some trouble with the code below. I am attempting to retrieve the values of the selected options from my layout_select2. Currently, when I select 'multi_select' and then an option from 'layout_select2', I end up with the first v ...

AngularJS bracket-enhanced template

Why is AngularJS giving an error when brackets are used inside ng-template content? I am trying to create an input field that should accept an array, but I keep getting this error message: "Error: Syntax Error: Token ']' not a primary expression ...

Sorting by Date in JavaScript

My goal is to filter out the elements in an array that have a date (converted from string) greater than a specific date. _this.downloadData.forEach(_d => _d.LogTime = _d.LogTime.toString()); console.log(_this.downloadData.filter(x=>new Date(x.LogTi ...

"Create a dynamic HTML newsletter utilizing tables similar to the responsive design principles

Looking to create a mobile-responsive newsletter using my style.css <table cellpadding="0" cellspacing="0" border="0" align="center" width="600" bgcolor="#fff"> <tbody> <tr> <td style="padding-bottom:5px" valign="top"&g ...

What is the best way to insert a YouTube video into a WordPress template page?

I decided to create a new template page for one of the pages on my WordPress site because I only wanted to have some text and a YouTube video displayed. It turns out that embedding a YouTube video directly into the code is not supported by WordPress, so I ...

Is it possible to create an HTML textarea that supports HTML formatting?

Is it possible to have HTML tag support in an HTML textarea within a form, similar to what is seen on Stack Overflow when asking a question? I would like to be able to capture the user's input in a textarea using PHP and print exactly what the user ty ...